Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum rows based on ID

Tags:

r

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
like image 675
dagan Avatar asked Oct 29 '15 07:10

dagan


1 Answers

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]
like image 140
akrun Avatar answered Oct 06 '22 00:10

akrun