【发布时间】:2010-11-26 14:34:40
【问题描述】:
使用 lapply 和friends 编写的代码通常比循环更容易看,也更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
如果我使用了 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 时应该怎么做?
【问题讨论】:
-
这可能是一个不受欢迎的回应,但经过 15 年的 R 开发,我几乎总是发现暂时转换为 for 循环以找到破坏我的代码的边缘情况更容易。此外,从 for 循环开始而不是 sapply/lapply 可以简化您的初始过程(您可以在重要时重构代码以提高速度/性能 - 但首先它需要工作!)
标签: r