Created
March 12, 2024 17:42
-
-
Save andrewheiss/4a1cb1af97af36797400681c9b91b1c8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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