问题
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