使用lapply和朋友编写的代码通常在眼睛上更容易,而且比循环更容易Rish.我和下一个人一样喜欢lapply,但是当出现问题时如何调试呢?例如:
> ## 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
Run Code Online (Sandbox Code Playgroud)
我使用了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
Run Code Online (Sandbox Code Playgroud)
但我会知道错误发生在哪里:
> i
[1] 2
Run Code Online (Sandbox Code Playgroud)
使用lapply/sapply时我该怎么办?
Sha*_*ane 23
如果使用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"
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您可以看到哪个索引失败.
小智 23
使用标准的R调试技术可以在发生错误时准确停止:
options(error = browser)
Run Code Online (Sandbox Code Playgroud)
要么
options(error = recover)
Run Code Online (Sandbox Code Playgroud)
完成后,恢复标准行为:
options(error = NULL)
Run Code Online (Sandbox Code Playgroud)
使用plyr包,包括.inform = TRUE:
library(plyr)
laply(x, function(x) 1/x, .inform = TRUE)
Run Code Online (Sandbox Code Playgroud)