expand.grid(country = c('Sweden','Norway', 'Denmark','Finland'),
sport = c('curling','crosscountry','downhill')) %>%
mutate(medals = sample(0:3, 12, TRUE)) ->
data
Using reshape2's dcast achieves this in one line. Using custom names for the margins require extra steps.
library(reshape2)
data %>%
dcast(country ~ sport, margins = TRUE, sum) %>%
# optional renaming of the margins `(all)`
rename(Total = `(all)`) %>%
mutate(country = ifelse(country == "(all)", "Total", country))
My dplyr + tidyr approach is verbose. What is the best (compact and readable) way of writing this using tidyr and dplyr.
library(dplyr)
library(tidyr)
data %>%
group_by(sport) %>%
summarise(medals = sum(medals)) %>%
mutate(country = 'Total') ->
sport_totals
data %>%
group_by(country) %>%
summarise(medals = sum(medals)) %>%
mutate(sport = 'Total') ->
country_totals
data %>%
summarise(medals = sum(medals)) %>%
mutate(sport = 'Total',
country = 'Total') ->
totals
data %>%
bind_rows(country_totals, sport_totals, totals) %>%
spread(sport, medals)