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

      

+3


source to share


3 answers


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.

+4


source


It doesn't work because you are trying to subset with list

, hence the error message you missed. If you have your heart set using a double lapply

, you can the unlist

inside.



lapply(data[unlist(lapply(data, is.numeric))], mean)

      

+4


source


Better to use

data %>% summarize_if(is.numeric, mean)

      

0


source







All Articles