Skip Error and Continue Function in R

…衆ロ難τιáo~ 提交于 2019-12-08 13:35:23

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/28598713/skip-error-and-continue-function-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!