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

Element-wise addition of list of data frames in R

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?

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 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
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