简体   繁体   English

R中数据框列表的逐元素添加

[英]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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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