gpt4 book ai didi

r - tryCatch 错误

转载 作者:行者123 更新时间:2023-12-02 00:39:14 27 4
gpt4 key购买 nike

我有一段代码,其中使用 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 是分析文件的名称列表。

所以,我正在尝试打印导致问题的文件名。

我的代码得到的traceback是:

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"

最佳答案

由于拼写错误 error,您收到“错误的处理程序规范”错误tryCatch 的参数.只有=可用于指定参数名称,例如

tryCatch(stop("no"), error = function(e) cat("Error: ",e$message, "\n"))

这也是错误没有被捕获的原因。请注意,按名称指定参数与赋值(创建绑定(bind))不同。在后者中,您可以使用 <- (它有时是首选,因为它清楚地表明这是一项任务)以及 = .在前者中,您只能使用 = .

关于r - tryCatch 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47772047/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com