简体   繁体   中英

how to add values to a new column in R with respect to an existing column's value

I have a 10 different dataframe.

dataframe named 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

I want to get the total calories (I did sum(Group1$calories) and worked fine). Similarly I have 9 groups. Now I have another data frame called participants:

> 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

I want to add a new column named total calorie with values of those total calories I calculated earlier. But the problem is I want the total calories of dataframe Group one to be put on the Row with G1 and respectively.

If you have dataframes Group1 , Group2 , Group3 ... Group10 you can try to get all the dataframes in a list, get sum of calories column in each dataframe and merge with participants dataframe.

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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