Combine rows with two matching columns in R

时间:2019-01-09 22:32:02

标签: r

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.

1 个答案:

答案 0 :(得分:0)

library(tidyverse)    
df %>%
  group_by(Year,Country) %>%
  summarise(Sales = sum(Sales))