在R中跳过错误并继续功能 [英] Skip Error and Continue Function in R

查看:993
本文介绍了在R中跳过错误并继续功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我在想什么(伪代码):

  for(i in ncol(data)){
try(hist(data [i])){
if错误尝试(barplot(data [i])){
如果errorprint(Error)}
}
继续执行i#代码执行所有数据列




$ b我尝试过使用try()和tryCatch()基于其他stackoverflow职位,但我似乎无法弄清楚如何工作。

解决方案

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


I have a data set with p number of variables. I want a function that creates histograms of each variable, and when it encounters a problem it attempts to create a barplot instead. If it encounters a problem after attempting the barplot it skips that p, and continues to the next p.

What I'm thinking (pseudocode):

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
    }
}

I've tried using the try() and tryCatch() based on other stackoverflow posts, but I can't seem to figure out how to work it.

解决方案

You probably want to use tryCatch for this. Something like the following should do the trick (though I can't test it since you don't provide any data).

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')
    })
  })  
}

这篇关于在R中跳过错误并继续功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆