Home > Enterprise >  Element-wise addition of list of data frames in R
Element-wise addition of list of data frames in R

Time:12-21

The answer to this question shows you can add two data frames (with the same dimensions) element-wise using ' '.

I have a list of data frames of the same dimensions, and I would like to return the element-wise sum of all the data frames. Since the length of the list can vary, I do not want to do something like

mylist[[1]]   mylist[[2]]   ...

I know I can write a loop to calculate the sum, but is there a simpler way to do this?

CodePudding user response:

You can use Reduce

Reduce(" ", your_list)

Example:

d1 <- data.frame(x=1:3, y=4:6)
d2 <- data.frame(z=4:6, w=6:4)
l <- list(d1, d2)
Reduce(" ", l) 
  x  y
1 5 10
2 7 10
3 9 10
  •  Tags:  
  • r
  • Related