[英]how to add values to a new column in R with respect to an existing column's value
我有 10 个不同的 dataframe。
dataframe 命名为 Group1:
ï.. calories components
1 meal1 177 150 oats + 250 skimmed milk
2 snack1 145 200 yougurt + 100 blackberries
3 meal2 560 200 beans + 100 lamb
4 snack2 66 apple
5 meal3 160 1pc crumpet + 25 spread cheese
我想得到总卡路里(我做了 sum(Group1$calories) 并且工作正常)。 同样,我有 9 个组。 现在我有另一个名为参与者的数据框:
> participants SubjectId Gender Groups ExtraCalories GW
1 1 F G3 -1310.000000 0.000000
2 2 M G6 -920.796555 4.331278
3 3 M G2 -25.395170 4.727376
4 4 M G1 169.256448 3.543941
5 5 M G4 -340.672353 4.591774
我想添加一个名为总卡路里的新列,其中包含我之前计算的总卡路里值。 但问题是我希望将 dataframe 第一组的总卡路里分别放在 G1 和 G1 的行上。
如果您有数据框Group1
, Group2
, Group3
... Group10
您可以尝试获取列表中的所有数据框,获取每个 dataframe 中calories
列的总和,并与participants
dataframe merge
。
merge(transform(stack(sapply(mget(paste0('Group', 1:10)), function(x)
sum(x$calories))), ind = paste0('G', 1:10)),
participants, by.x = "ind", by.y = "Groups")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.