library(knitr)
suppressMessages(library(tidyverse))
library(fivethirtyeight)
library(fivethirtyeightdata)
Convert fivethirtyeightdata drinks dataframe (wide format) into a tibble:
drinksTibble <- as_tibble(drinks)
Drop total_litres_of_pure_alcohol column and all countries except USA, Seychelles, Iceland and Greece:
drinksTibble <- drinksTibble %>% select(-total_litres_of_pure_alcohol) %>% filter(country %in% c("USA", "Seychelles", "Iceland", "Greece"))
Rename columns to country, beer, spirit and wine - display head (wide format):
names(drinksTibble) <- c("country", "beer", "spirit", "wine")
head(drinksTibble)
## # A tibble: 4 x 4
## country beer spirit wine
## <chr> <int> <int> <int>
## 1 Greece 133 112 218
## 2 Iceland 233 61 78
## 3 Seychelles 157 25 51
## 4 USA 249 158 84
Break out combined type/servings combined variable and arrange by country name - display head (long format):
drinksTibbleLong <- gather(drinksTibble, type, servings, -c(country)) %>% arrange(country)
head(drinksTibbleLong)
## # A tibble: 6 x 3
## country type servings
## <chr> <chr> <int>
## 1 Greece beer 133
## 2 Greece spirit 112
## 3 Greece wine 218
## 4 Iceland beer 233
## 5 Iceland spirit 61
## 6 Iceland wine 78
Display horizontal bar char with geom_col where the source data is our long format tibble, x-axis is servings, y-axis is country, fill by type and stack side-to-side (e.g., dodge):
ggplot(data = drinksTibbleLong, aes(x = servings, y = country, fill = type)) +
geom_col(position = "dodge")