use*_*347 17 statistics r
我正在阅读几个*.csv,其中名称和路径是在运行时确定的.
但是有时候有些文件不存在.对于这个文件,我需要一些异常处理.
目前我正在阅读我的文件:
companyFileName <- paste("C://Users//Prices//",companiesIsin,".csv")
df <- read.csv(gsub(" ","", companyFileName, fixed=TRUE), header = TRUE, sep = ";",stringsAsFactors=FALSE)
Run Code Online (Sandbox Code Playgroud)
当文件夹中不存在该文件时,我收到错误.R中有异常处理吗?
感谢您的回复!
Mar*_*ann 31
您可以使用该功能检查文件是否存在file.exists.因此,您可以在尝试读取之前检查文件是否存在以避免错误,例如
if (file.exists(companyFileName))
df <- read.csv(gsub(" ","", companyFileName, fixed=TRUE), header = TRUE, sep = ";",stringsAsFactors=FALSE)
Run Code Online (Sandbox Code Playgroud)
编辑:您还可以简化路径的创建并使用read.csv2作为;分隔符.这使它更具可读性.
f <- paste0("C://Users//Prices//",companiesIsin,".csv")
if (file.exists(f))
df <- read.csv2(f, TRUE, stringsAsFactors=FALSE)
Run Code Online (Sandbox Code Playgroud)