MJP
MJP

Reputation: 99

Calculating proportion by year using dplyr

I'm attempting to calculate the frequency a variable (in this case country) shows up in any given year. For example:

name <- c('AJ Griffin','Steve Bacon','Kevin Potatoe','Jose Hernandez','Kent Brockman',
                  'Sal Fasno','Kirk Kelly','Wes United','Livan Domingo','Mike Fast')

country <- c('USA', 'USA', 'Canada', 'Dominican Republic', 'Panama', 'Dominican Republic', 'Canada', 'USA', 'Dominican Republic', 'Mexico') 

year <- c('2016', '2016', '2016', '2016', '2016', '2015', '2015', '2015', '2015', '2015') 

country_analysis <-data.frame(name, country, year)

When I use the following code I get the proportion of countries for the entire dataset, but I would like to pare this down even further to specific years.

P <- country_analysis %>% 
  group_by(country) %>%     
  summarise(n=n())%>%
  mutate(freq = round(n / sum(n), 1))

Ideally the end result would have country, year, frequency column (i.e. 2016, USA, 0.4). Any input would be appreciated.

Upvotes: 1

Views: 499

Answers (1)

MrFlick
MrFlick

Reputation: 206242

First collapse by year and country, then by just year. For example

country_analysis %>% 
  group_by(year, country) %>% 
  summarize(count=n()) %>% 
  mutate(proportion=count/sum(count))

#     year            country count proportion
#   <fctr>             <fctr> <int>      <dbl>
# 1   2015             Canada     1        0.2
# 2   2015 Dominican Republic     2        0.4
# 3   2015             Mexico     1        0.2
# 4   2015                USA     1        0.2
# 5   2016             Canada     1        0.2
# 6   2016 Dominican Republic     1        0.2
# 7   2016             Panama     1        0.2
# 8   2016                USA     2        0.4

Upvotes: 6

Related Questions