[英]Skip Error and Continue Function in R
I have a data set with p number of variables. 我有一个带有p个变量的数据集。 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.
如果在尝试小节图后遇到问题,它将跳过该p,并继续到下一个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. 我已经尝试过根据其他stackoverflow帖子使用try()和tryCatch(),但是我似乎无法弄清楚它是如何工作的。
You probably want to use tryCatch
for this. 您可能要为此使用
tryCatch
。 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')
})
})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.