ith.error <- NULL
bar <- function(i){
ith.error <<- append(ith.error,i)
return(ith.error)
}
for(i in c(2,3,5,"p",6)){
tryCatch(
{cat(log(i),"\n")},
error=function(e){bar()} #**
)
}
尝试使用tryCatch在for循环中记录任何失败的第i次迭代,
ith.error
的输出应为4(矢量格式,给定输入的索引位置)
**在该特定行上尝试了许多版本:
ith.error[i] <- i #version 1 doesn't work
h = bar(i) #version 2 didn't work too
答案 0 :(得分:2)
您忘记将i
输入bar
功能。另请注意,c(2,3,5,"p",6)
是character
向量,您无法将log
应用于其任何元素。请改用list
。
ith.error <- NULL
bar <- function(i){
ith.error <<- append(ith.error,i)
return(ith.error)
}
for(i in list(2,3,5,"p",6)){
tryCatch(
{cat(log(i),"\n")},
error=function(e){bar(i)} #**
)
}
ith.error
#[1] "p"