I have two columns with id and value. I am trying to sum all rows with the same ID . I am trying to create this as a separate column without using the aggregate function. Preferably using base
R as I am trying to create a calculated field in the Radiant app
ID value
456 4
456 5
781 10
781 1
123 5
321 3
123 8
321 12
Looking for a result as below
ID total
456 9
456 9
781 11
781 11
123 13
321 15
123 13
321 15
We can use dplyr
. We group by 'ID' and then transmute
to create a new column 'Total' as the sum
of 'value'.
library(dplyr)
df1 %>%
group_by(ID) %>%
transmute(Total=sum(value))
Or use ave
from base R
to get the sum
of 'value' grouped by 'ID' to transform
the dataset to create a new column.
transform(df1, Total= ave(value, ID, FUN=sum))[-2]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With