R: sapply works but
I am trying to better understand the difference between lappie and nozzle. In the example below, why later work but not the first one?
# 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
source to share
lapply
returns a default list:
From the documentation:
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
returns the default vector:
From the documentation:
sapply is a convenience version and wrapper by default by returning a vector.
So when you slice / multiply a data.frame like this data[sapply(data, is.numeric)]
one you need to pass in a vector of elements, otherwise it won't work. And so it sapply
works, it lapply
doesn't work.
source to share