[英]sum of one column (with same name) in all data frames in a list
How can I sum one specific column in all data frames in a list an put them in a new data frame? 如何将列表中所有数据框中的一个特定列相加并将它们放入新数据框中? An small example is: 一个小例子是:
A <- data.frame(matrix( nrow = 2, ncol = 2))
B <- data.frame(matrix( nrow = 2, ncol = 2))
A[,] <- 3
B[,] <- 4
l <- list(A,B)
So let's say I want to sum up all columns "X1" in my list and put in one data frame (vector, since there only should be one row). 所以,假设我想在我的列表中总结所有列“X1”并放入一个数据框(向量,因为只有一行)。 This data frame should then have value 6 (3+3) in first row and 8 (4+4) in the second. 然后,该数据帧的第一行应为6(3 + 3),第二行为8(4 + 4)。
In the real data I have 18 data frames in the list and the columns to sum in each data frame is of different lenght. 在实际数据中,列表中有18个数据帧,每个数据帧中要求和的列具有不同的长度。
Mabye I should use the sapply
or lapply
function? Mabye我应该使用sapply
或lapply
函数?
You can use colSums
, ie 你可以使用colSums
,即
do.call(rbind, lapply(l, function(i)colSums(i['X1'])))
# X1
#[1,] 6
#[2,] 8
Here is one option with sapply
where we Extract
the column 'X1' into a matrix
and then do the colSums
这里有一个sapply
选项,我们将列'X1' Extract
到matrix
,然后执行colSums
colSums(sapply(l, `[[`, 'X1'))
#[1] 6 8
Or with map
from purrr
或者使用purrr
map
library(purrr)
library(dplyr)
map_dbl(l, ~ .x %>%
pull(X1) %>%
sum)
#[1] 6 8
If it is needed as a data.frame 如果需要它作为data.frame
map_dfr(l, ~ .x %>%
summarise(X1 = sum(X1)))
# X1
#1 6
#2 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.