[英]Error in tryCatch
我有一个代码,其中使用for循环读取和分析文件列表。 由于我必须分析几个文件,我想使用tryCatch来打印引发问题的文件的名称。 我的文件存在的一个常见问题是列名称是错误的,我的意思是,它会出现在文件中:
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])
})
其中files是所分析文件名称的列表。
所以,我正在尝试打印导致麻烦的文件名。
我的代码获得的回溯是:
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)
我以前从未使用过tryCatch,所以可能是一个条件问题,但我不确定。
谢谢!
我有一个新的代码是:
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"
由于tryCatch
的拼写error
参数,您收到“错误的处理程序规范”错误。 Only =
可用于指定参数名称,例如
tryCatch(stop("no"), error = function(e) cat("Error: ",e$message, "\\n"))
这也是错误未被发现的原因。 请注意,按名称指定参数与赋值(创建绑定)不同。 在后者中,你可以使用<-
(它有时是首选,因为它表明它是一个赋值)以及=
。 在前者中,您只能使用=
。
不是tryCatch解决方案。 循环遍历文件名,检查它是否存在,然后检查数据帧是否具有正确的名称。 像这样的东西(未经测试):
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) ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.