Skip to content

Instantly share code, notes, and snippets.

@jimjam-slam
Created February 11, 2022 05:55
Show Gist options
  • Save jimjam-slam/3d2fccb8372be62c26b379974403b6e2 to your computer and use it in GitHub Desktop.
Save jimjam-slam/3d2fccb8372be62c26b379974403b6e2 to your computer and use it in GitHub Desktop.
Pipe for getting the unique values of every factor column #rstatstips
get_factor_values <- . %>%
summarise(across(
where(is.factor),
list(
n = ~ length(levels(.x)),
# could also pivot longer so that there's a row for each level...
pos_values = ~ paste(levels(.x), collapse = "|")),
.names = "{.col}-{.fn}"
)) %>%
pivot_longer(everything(), names_to = c("col_name", ".value"),
names_sep = "-")
starwars %>%
# convert character cols to factors
mutate(across(where(is.character), ~ factor(.x))) %>%
get_factor_values()
# # A tibble: 8 × 3
# col_name n pos_values
# <chr> <int> <chr>
# 1 name 87 Ackbar|Adi Gallia|Anakin Skywalker|Arvel Crynyd|Ayla Secura|…
# 2 hair_color 12 auburn|auburn, grey|auburn, white|black|blond|blonde|brown|b…
# 3 skin_color 31 blue|blue, grey|brown|brown mottle|brown, white|dark|fair|fa…
# 4 eye_color 15 black|blue|blue-gray|brown|dark|gold|green, yellow|hazel|ora…
# 5 sex 4 female|hermaphroditic|male|none
# 6 gender 2 feminine|masculine
# 7 homeworld 48 Alderaan|Aleen Minor|Bespin|Bestine IV|Cato Neimoidia|Cerea|…
# 8 species 37 Aleena|Besalisk|Cerean|Chagrian|Clawdite|Droid|Dug|Ewok|Geon…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment