简体   繁体   中英

Summing elements of a list in r

I have a list with 10 elements, and each element contains two variables.

$`1.10%.100`
   sqm      tempo 
127.4444   0.1500 

$`10.10%.100`
   sqm      tempo 
 367.00    0.16 

$`2.10%.100`
   sqm      tempo 
248.7778   0.1900 

$`3.10%.100`
   sqm      tempo 
 139.00    0.13 

$`4.10%.100`
   sqm      tempo 
 139.00    0.14 

$`5.10%.100`
   sqm      tempo 
 223.00    0.17 

$`6.10%.100`
   sqm      tempo 
155.4444   0.1500 

$`7.10%.100`
   sqm      tempo 
248.7778   0.1400 

$`8.10%.100`
   sqm      tempo 
90.11111  0.14000 

$`9.10%.100`
   sqm      tempo 
90.11111  0.17000 

I want to calculate the average, two by two, and fill this in a new list.

For example i want: mean(127.4444, 367.00) and mean(0.15, 0.16)...the same for elements 3 and 4, 5 and 6, and so on.

You could try:

#generate some sample data hopefully similar to yours
set.seed(1)
#set the size of the aggregation (you can change it to 10 for instance)
n<-2
mylist<-replicate(10,c(sqm=runif(1,100,1000),tempo=runif(1)),simplify=FALSE)
matrix(colMeans(`dim<-`(do.call(rbind,mylist),c(n,length(mylist)/n*2))),ncol=2)
#         [,1]      [,2]
#[1,] 477.2629 0.6401658
#[2,] 615.8607 0.7795937
#[3,] 475.7899 0.1191715
#[4,] 755.5889 0.4409015
#[5,] 593.9442 0.8846757

First column you got the averages of the sqm elements, on the other column the tempo averages.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM