Debugging lapply/sapply calls
r
Solution
Use the standard R debugging techniques to stop exactly when the error occurs:
options(error = browser)
or
options(error = recover)
When done, revert to standard behaviour:
options(error = NULL)
Problem
Code written using lapply and friends is usually easier on the eyes and more Rish than loops. I love lapply just as much as the next guy, but how do I debug it when things go wrong? For example: ``` > ## 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 ``` Had I used a for loop: ``` > 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 ``` But I would know where the error happened: ``` > i [1] 2 ``` What should I do when using lapply/sapply?