使用lapply和friends编写的代码通常看起来更美观,而且比循环更具Rish。我和其他人一样喜欢,但是我怎么在出错的时候调试它呢?例如:
> ## a list composed of numeric elements
> x <- as.list(-2:2)
> ## turn one of the elements into characters
> x[[2]] <- "what?!?"
>
> ## using sapply
> sapply(x, function(x) 1/x)
Error in 1/x : non-numeric argument to binary operator如果我使用了for循环:
> y <- rep(NA, length(x))
> for (i in 1:length(x)) {
+ y[i] <- 1/x[[i]]
+ }
Error in 1/x[[i]] : non-numeric argument to binary operator但我会知道错误发生在哪里:
> i
[1] 2当我使用lapply/sapply时,我应该怎么做?
发布于 2009-09-09 20:40:01
使用标准的R调试技术准确地在错误发生时停止:
options(error = browser) 或
options(error = recover)完成后,恢复为标准行为:
options(error = NULL)发布于 2009-09-08 18:59:01
如果你用try()语句包装你的内部函数,你会得到更多信息:
> sapply(x, function(x) try(1/x))
Error in 1/x : non-numeric argument to binary operator
[1] "-0.5"
[2] "Error in 1/x : non-numeric argument to binary operator\n"
[3] "Inf"
[4] "1"
[5] "0.5"在这种情况下,您可以看到哪个索引失败。
发布于 2009-09-08 23:48:11
使用带有.inform = TRUE的plyr包
library(plyr)
laply(x, function(x) 1/x, .inform = TRUE)https://stackoverflow.com/questions/1395622
复制相似问题