I'm sure there's a question similar to this already, but I couldn't make them work
I am trying to calculate aggregates (or subtotals) in a dataframe of long format. In the group column I want an aggregate variable "AGG" that is a sum of "value" for a specific "Year" and "var". I have tried using the aggregate() function, but didn't succeed. I used the code:
aggregate(value ~ cbind(Year,var), data = Energi5, FUN = sum)
My data looks like this
> head(df)
Year group var value
1 1966 A x 25465462
2 1966 B x 9512621
3 1966 E x 2832865
4 1966 H x 291769
5 1966 NE x 141524912
6 1966 NF x 23580353
> tail(df)
Year group var value
5403 2017 NZ y 167158
5404 2017 O y 23480
5405 2017 QF y 0
5406 2017 QS y 0
5407 2017 QZ y 16447
5408 2017 TC3000 y 488556
and I would like to obtain something like this at the end of (or in the middle of) my existing dataframe
Year group var value
5409 1966 AGG x ?
5410 1967 AGG x ?
...
5450 2017 AGG x ?
5451 1966 AGG y ?
...
I hope you can help. Thank you!