-2

I need to convert monthly observations into annual -- year-country instead of month-country.

This is how the data looks:

year    month   countrycode troop
1990    1            USA    6
1990    2            USA    4
1990    3            CANADA 3
1990    4            CANADA 6
1991    1            USA    5
1991    2            USA    6
1991    3            CANADA 3
1991    4            CANADA 6

I would like to convert this into:

year    countrycode troop
1990         USA    10
1990         CANADA 9
1991         USA    11
1991         CANADA 9

I have no clue how to start so I'm grateful for all suggestions!

FKG
  • 285
  • 1
  • 4
  • 17
  • 3
    You need a group by sum `library(dplyr);df1 %>% group_by(year, countrycode) %>% summarise(troop = sum(troop))` – akrun Mar 01 '18 at 09:49
  • Thanks! This worker great! May also ask how to group by sum if I want to do it for more than one variable? I tried: `df1 %>% group_by(year, countrycode) %>% summarise(troop = sum(troop), police=sum(police))` but it did not work. – FKG Mar 01 '18 at 13:51

1 Answers1

1

I would use aggregate:

df_annual <- aggregate(troop ~ year + countrycode, df_monthly, sum)
Jordi
  • 1,313
  • 8
  • 13