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