简体   繁体   中英

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?

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

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