Death Metal
Death Metal

Reputation: 892

sum and average of rows from list of data frames

I'm interested to sum each row from list of data frames. That is first row needs to be summed across all the data frame in the list. Likewise, second and such. Once the addition is complete, I'd like to take the average by the number of data frames in the list. I do it with the following code (tedious)

sample_list<-list(data.frame(x=c(1:5)),data.frame(x=c(6:10)), data.frame(x=c(11:15)) ) ## sample data frame's list

sum_per_person<-matrix(nrow=nrow(sample_list[[1]]),ncol=1) ## create a matrix to store sum of each row from the list of data frames.

number_indi=nrow(sample_list[[1]]) ## number of rows are same in each data frame within the list

iterate_person=1 ## set counter 

while(iterate_person<=number_indi){ ## do a while loop

sum_temp=0 ## set to zero
for(x in 1:length(sample_list)){
## iterate over the sample list
sum_temp<-sum_temp+(sample_list[[x]])[iterate_person,]

} ## iteration ends for the list

sum_per_person[iterate_person,1]<-sum_temp
iterate_person<-iterate_person+1 ## increment 
} ## for loop ends 

## take average
sum_per_person<-sum_per_person/length(sample_list) ## final result 

Is there a way I can accomplish this in non-complicated way via lapply, apply?

Upvotes: 1

Views: 290

Answers (1)

akrun
akrun

Reputation: 887501

Instead of the while loop, an option in R would be to get the sum of corresponding elements of list with Reduce and divide by the length of the 'sample_list'

Reduce(`+`, sample_list)/length(sample_list)
#  x
#1  6
#2  7
#3  8
#4  9
#5 10

Or a concise approach is rowMeans after converting it to a single data.frame

rowMeans(do.call(cbind, sample_list))

Upvotes: 1

Related Questions