-1

I have a df that resembles this:

Year Country   Sales($M)
2013 Australia 120
2013 Australia 450
2013 Armenia   80
2013 Armenia   175
2013 Armenia   0
2014 Australia 500
2014 Australia 170
2014 Armenia   0
2014 Armenia   100

I'd like to combine the rows that match Year and Country, adding the Sales column. The result should be:

Year Country   Sales($M)
2013 Australia 570
2013 Armenia   255
2014 Australia 670
2014 Armenia   100

I'm sure I could write a long loop to check whether Year and Country are the same and then add the Sales from those rows, but this is R so there must be a simple function that I'm totally missing.

Many thanks in advance.

Jay D.
  • 5
  • 2
  • The keyword you need to search for is "by_group" or "group_by. See multiple solutions here: https://stackoverflow.com/questions/1660124/how-to-sum-a-variable-by-group – Adam Sampson Jan 09 '19 at 22:36
  • The base R solution is `aggregate(Sales ~ Year + Country, data = df1, sum)` where `df1` is the data frame. – neilfws Jan 09 '19 at 22:39

1 Answers1

0
library(tidyverse)    
df %>%
  group_by(Year,Country) %>%
  summarise(Sales = sum(Sales))
Eric
  • 1,381
  • 9
  • 24