tryCatch中的错误
我有一个代码,其中使用for循环读取和分析文件列表。由于我必须分析几个文件,所以我想使用tryCatch打印出现问题的文件名。我的文件存在的一个常见问题是列名有误,我的意思是,它可能在文件中:tryCatch中的错误,r,R,我有一个代码,其中使用for循环读取和分析文件列表。由于我必须分析几个文件,所以我想使用tryCatch打印出现问题的文件名。我的文件存在的一个常见问题是列名有误,我的意思是,它可能在文件中: ID; close; description 1;20-12-2017;0.5;"description1" 而不是 ID; date; close; description 1;20-12-2017;0.5;"description1" 这显然会引起错误,因为列名的数量与列的数量不匹配 为了检测此错
ID; close; description
1;20-12-2017;0.5;"description1"
而不是
ID; date; close; description
1;20-12-2017;0.5;"description1"
这显然会引起错误,因为列名的数量与列的数量不匹配
为了检测此错误,我将执行以下代码:
for (i in 1:length(files)){
tryCatch({
name<-as.character(files[i])
dat<-read.table(name,header = T,sep="@",dec=",",comment.char = "")
},
error<-function(e){
print("error in file",files[i])
})
不是tryCatch解决方案。循环遍历文件名,检查它是否存在,然后检查dataframe是否具有正确的名称。类似于此(未经测试):
myList由于error
到tryCatch
的参数拼写错误,您收到了“错误的处理程序规范”错误。只有=
可用于指定参数名称,例如
tryCatch(停止(“否”),错误=功能(e)cat(“错误:”,e$消息“\n”))
这也是错误没有被捕获的原因。请注意,按名称指定参数与赋值(创建绑定)不同。在后者中,您可以使用,问题是读取文件时可能会出现不同的错误,不仅仅是列名和编号,这是一个示例错误
3.stop("bad handler specification")
2.tryCatch({
name <- as.character(files[i])
dat <- read.table(name, header = T, sep = "@", dec = ",",
comment.char = "") ...
1.data_function(files)
for (j in 1:length(files)){
name<-as.character(files[j])
possibleError<-tryCatch({
dat<-read.table(name,header = T,sep="@",dec=",",comment.char = "")
},
warning = function(w) {
print(paste("Warning:", w, "in file:", name))
},
error<-function(e){
print(paste("Error:", e, "in file:",name))
},
finally = {
print(paste("End proc. :", name))
}
)
if(!inherits(possibleError, "error")) {
# do things
}
else{next}
}
[1] "End proc. : C:\\TimeSeries_RiskFactors\\20171119\\C0.GBMRISK.1100000156062.txt"
[1] "End proc. : C:\\TimeSeries_RiskFactors\\20171119\\C0.GBMRISK.1100000156063.txt"
[1] "End proc. : C:\\TimeSeries_RiskFactors\\20171220\\C0.GBMRISK.1100000156064.txt"
Show Traceback
Rerun with Debug
Error in read.table(name, header = T, sep = "@", dec = ",", comment.char = "") :
duplicate 'row.names' are not allowed
[1]"End proc. : C:\\TimeSeries_RiskFactors\\20171220\\C0.GBMRISK.1100000156065.txt"
myList <- lapply(myFiles, function(i){
if(file.exists(i)){
res <- paste(i, "File doesn't exist.")
} else {
res <- read.table(i)
if(!identical(colnames(res), c("ID", "date", "close", "description")){
res <- paste(i, "File wrong columns")
}
}
#return
res
}))
# my dataframes with correct column names
myListDF <- myList[ sapply(myList, is.data.frame) ]
# failed files
myListErrors <- myList[ !sapply(myList, is.data.frame) ]