gpt4 book ai didi

r - 对数据框列表中的列求和

转载 作者:行者123 更新时间:2023-12-04 02:11:14 28 4
gpt4 key购买 nike

我想从数据框列表中生成一个数据框,其中所有列都相同,除了一列“收入”应该是列表中所有“收入”的总和。

这是我的数据框列表

mylist= structure(list(`1` = structure(list(ID = c(36L, 37L, 38L, 39L), Income = c(0, 0, 0, 9100)), .Names = c("ID", "Income"), row.names = c(1L, 2L, 3L, 4L), class = "data.frame"), `2` = structure(list(ID = c(36L, 37L, 38L, 39L), Income = c(0, 0, 0, 0)), .Names = c("ID", "Income"), row.names = c(1L, 2L, 3L, 4L), class = "data.frame"), `3` = structure(list(ID = c(36L, 37L, 38L, 39L), Income = c(7360, 0, 0, 0)), .Names = c("ID", "Income"), row.names = c(1L, 2L, 3L, 4L), class = "data.frame")))

> mylist
$`1`
ID Income
1 36 0
2 37 0
3 38 0
4 39 9100

$`2`
ID Income
1 36 0
2 37 0
3 38 0
4 39 0

$`3`
ID Income
1 36 7360
2 37 0
3 38 0
4 39 0

这就是我想要做的:
   ID   Income
34 36 7360
26 37 0
23 38 0
15 39 9100

我曾尝试使用 reduce() 进行求和,但它创建了一个我想避免的单独列:
Reduce(function(df1, df2) data.frame(df1[,], res=df1["Income"] + df2["Income"]),mylist)

最佳答案

如果 'ID's 在不同的 list可以不同,我们merge使用 Reduce 的数据集,然后执行 rowSums除了第一个创建“收入”列的输出。

r1 <- Reduce(function(...) merge(..., by = "ID"), mylist) 
data.frame(r1[1], Income = rowSums(r1[-1]))
# ID Income
#1 36 7360
#2 37 0
#3 38 0
#4 39 9100

如果 list 中所有数据集的“ID”相同且顺序相同,我们创建了 data.frame通过从“mylist”的第一个元素中提取“ID”并使用 Reduce 获得“收入”的总和与 + .
data.frame(mylist[[1]][1], Reduce(`+`, lapply(mylist, `[`, 'Income')))

关于r - 对数据框列表中的列求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38113478/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com