Noori11
Noori11

Reputation: 73

R: How to use functions in a deep nested list?

I'm trying to calculate the mean of the variable called disp for all 250 dataframes in my list called: lst.

for(i in 1:250){
lst[[i]] <- sample_n(mtcars, 25, replace = TRUE)

}

I can access disp in the first dataframe as lst[[1]][["disp"]], but how can I use sapply to calculate the mean value of disp in each of the 250 samples?

Upvotes: 0

Views: 58

Answers (1)

jyjek
jyjek

Reputation: 2707

With tidyverse:

library(tidyverse)

     lst%>%
       map("disp")%>%
       map_dbl(mean)

      [1] 254.552 257.404 256.164 214.312 227.660 237.824 221.176 221.648 236.804 232.252 212.948 227.620 242.904
     [14] 271.348 251.412 196.428 207.600 257.244 211.756 220.416 248.980 234.524 275.780 220.720 189.656 230.968

Upvotes: 3

Related Questions