R sum a variable by two groups [duplicate]

With data.table

library("data.table")

D <- fread(
"ID     Year     Amount  
3       2000      45  
3       2000      55  
3       2002      10  
3       2002      10  
3       2004      30  
4       2000      25  
4       2002      40  
4       2002      15  
4       2004      45  
4       2004      50"
)
D[, .(Amount=sum(Amount)), by=.(ID, Year)]

and with base R:

aggregate(Amount ~ ID + Year, data=D, FUN=sum)

(as commented by @markus)

Leave a Comment