【问题标题】:Skip Error and Continue Function in RR中的跳过错误和继续功能
【发布时间】:2015-02-19 04:41:35
【问题描述】:

我有一个包含 p 个变量的数据集。我想要一个创建每个变量的直方图的函数,当它遇到问题时,它会尝试创建一个条形图。如果在尝试 barplot 后遇到问题,它会跳过该 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
    }
}

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

【问题讨论】:

    标签: r for-loop try-catch histogram


    【解决方案1】:

    您可能想为此使用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')
        })
      })  
    }
    

    【讨论】:

    • 是的,这行得通。我改变了一件事: barplot(table()) 抱歉,我无法提供数据。我一直在尝试生成虚拟数据并遇到错误。 . .谢谢!
    猜你喜欢
    • 1970-01-01
    • 2019-12-06
    • 2019-12-05
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多