Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Calculate the mean value for each variable in multiple dataframes stored in single list

I was wondering if it’s possible to loop through the contents of a list, and calculate the mean values of all variables, across multiple dataframes. Here I’ve created an example list, containing three dataframes.

datalist <- list(a=mtcars[1:4, 1:2],b=mtcars[ 5:9 ,3:7],c=mtcars[10:15,8:11]) 
> datalist
$a
                mpg cyl
Mazda RX4      21.0   6
Mazda RX4 Wag  21.0   6
Datsun 710     22.8   4
Hornet 4 Drive 21.4   6

$b
                   disp  hp drat   wt  qsec
Hornet Sportabout 360.0 175 3.15 3.44 17.02
Valiant           225.0 105 2.76 3.46 20.22
Duster 360        360.0 245 3.21 3.57 15.84
Merc 240D         146.7  62 3.69 3.19 20.00
Merc 230          140.8  95 3.92 3.15 22.90

$c
                   vs am gear carb
Merc 280            1  0    4    4
Merc 280C           1  0    4    4
Merc 450SE          0  0    3    3
Merc 450SL          0  0    3    3
Merc 450SLC         0  0    3    3
Cadillac Fleetwood  0  0    3    4

I need to get the mean for each variable in each dataframe. The results I’d like to get in form of a list for each dataframe, containing the means for their respective variables. Any help greatly appreciated. Thanks

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can apply colMeans on each dataframe with the help of lapply

lapply(datalist, colMeans)

#$a
#  mpg   cyl 
#21.55  5.50 

#$b
#   disp      hp    drat      wt    qsec 
#246.500 136.400   3.346   3.362  19.196 

#$c
#       vs        am      gear      carb 
#0.3333333 0.0000000 3.3333333 3.5000000 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading