跳过错误并继续 R 中的函数

Skip Error and Continue Function in R

我有一个包含 p 个变量的数据集。我想要一个函数来创建每个变量的直方图,当它遇到问题时,它会尝试创建一个条形图。如果在尝试条形图后遇到问题,它会跳过那个 p,并继续下一个 p。

我在想什么(伪代码):

for (i in ncol(data)) {
    try( hist(data[i])) {
        if "error" try( barplot(data[i])) {
            if "error" print ("Error") }
        }
    continue to i # code executes through all columns of data
    }
}

我已经尝试使用基于其他 Whosebug 帖子的 try() 和 tryCatch(),但我似乎无法弄清楚如何使用它。

您可能想为此使用 tryCatch。像下面这样的东西应该可以解决问题(尽管我无法测试它,因为你没有提供任何数据)。

for(i in 1:ncol(d)) {
  tryCatch(hist(d[[i]], main=i), error=function(e) {
    tryCatch(barplot(d[[i]], main=i), error=function(e) {
      print('Error')
    })
  })  
}