我试图更好地理解 lapply 和 sapply 之间的区别。在下面的示例中,为什么后者有效,而前者无效?
# Data
data <- data.frame("A" = rnorm(500, 0, 1),
"B" = rnorm(500, 0, 1),
"C" = sample(c("a", "b" , "c"), 500, replace = T))
# Give the mean of all numeric elements in the dataframe.
lapply(data[lapply(data, is.numeric)], mean) # Doesn't work
Error in `[.default`(data, lapply(data, is.numeric)) :
invalid subscript type 'list'
lapply(data[sapply(data, is.numeric)], mean) # Works
最佳答案
lapply
默认返回一个列表:
来自文档:
lapply returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X.
sapply
默认返回一个向量:
来自文档:
sapply is a user-friendly version and wrapper of lapply by default returning a vector.
因此,当您像这样 data[sapply(data, is.numeric)]
对 data.frame 进行切片/子集时,您需要传递一个元素向量,否则它将无法工作。这就是为什么 sapply
有效而 lapply
无效的原因。
关于R: sapply 有效,但 lapply 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27603944/