使用lapply和朋友編寫的代碼通常比眼睛更容易,Rish比循環更多。我喜歡和下一個人一樣喜歡樂福,但是當出現問題時我該如何調試呢?例如:調試lapply/sapply調用
> ## 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
如果我用一個循環:
> 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時,我應該怎麼辦?
或者只是'blah <-sapply(x,mfn)'。而且你不應該同時需要'debug'和recover' – hadley