使用tryCatch记录第i次迭代失败

时间:2018-06-12 07:19:38

标签: r

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

1 个答案:

答案 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"