0

By "group" I mean rows with the same value in one of their columns, not the dplyr grouping. This is a sample dataframe I'm working with.

df <- data.frame("participant" = c("jack", "ellen", "ellen", "jack", "denise"),
                 "food" = c(a, a, b, c, a),
                 "quantity" = c(3, 6, 2, 34, 2))

#  participant food quantity
#1        jack    a        3
#2       ellen    a        6
#3       ellen    b        2
#4        jack    c       34
#5      denise    a        2

I would like to add a percentage column to this dataframe that is $quantity / sum $quantity for unique participant. Something like this:

  participant food quantity percent
1        jack    a        3       8
2       ellen    a        6      75
3       ellen    b        2      25
4        jack    c       34      92
5      denise    a        2     100

I would like it to be done automatically without me manually writing the values in per row. How would I write the code to do that?

0 Answers0