Skip to content

Instantly share code, notes, and snippets.

@andrewheiss
Created March 12, 2024 17:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewheiss/4a1cb1af97af36797400681c9b91b1c8 to your computer and use it in GitHub Desktop.
Save andrewheiss/4a1cb1af97af36797400681c9b91b1c8 to your computer and use it in GitHub Desktop.
library(tidyverse)
library(gapminder)
# ifelse() will happily work and coerce your numbers into text
gapminder1 <- gapminder |>
mutate(life_cat = ifelse(lifeExp > 75, "High", lifeExp))
# if_else() will yell at you
gapminder1 <- gapminder |>
mutate(life_cat = if_else(lifeExp > 75, "High", lifeExp))
# Nested ifelses() are gross
gapminder2 <- gapminder |>
mutate(is_africa_europe = if_else(continent == "Africa", "Africa", if_else(continent == "Europe", "Europe", "Not Africa or Europe")))
# case_when() lets you use multiple conditions
# For catch-all conditions, you can either specify a TRUE condition at the end
# (since it'll be the last-checked condition):
gapminder3 <- gapminder |>
mutate(is_africa_europe = case_when(
continent == "Africa" ~ "Africa",
continent == "Europe" ~ "Europe",
TRUE ~ "Not Africa or Europe"
))
# Or you can use the .default argument:
gapminder3 <- gapminder |>
mutate(is_africa_europe = case_when(
continent == "Africa" ~ "Africa",
continent == "Europe" ~ "Europe",
.default = "Not Africa or Europe"
))
# To recode values in a specific column, you can use a simplified version of
# case_when() called case_match()
gapminder4 <- gapminder |>
# Change specific categories
mutate(continent_different = case_match(continent,
"Africa" ~ "The African Continent",
.default = continent
)) |>
# Collapse categories
mutate(collapsed = case_match(continent,
c("Africa", "Asia") ~ "Africa or Asia",
.default = continent
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment