Skip to content

Instantly share code, notes, and snippets.

@matt-dray
Last active June 16, 2022 11:03
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 matt-dray/458ed29152ef46752b264e53016473bd to your computer and use it in GitHub Desktop.
Save matt-dray/458ed29152ef46752b264e53016473bd to your computer and use it in GitHub Desktop.
Some patterns for `dplyr::rename_with()` that I use frequently for wide datasets
# Some handy patterns with dplyr::rename_with()
# Matt Dray
library(dplyr, warn.conflicts = FALSE)
# 1. Extracting code from question code/label ----------------------------
x <- tibble(
Placeholder = LETTERS[1:3], # want to keep the same
"X01. Placeholder question text" = 1:3, # want 'X01'
"X02. Placeholder question text" = 1:3 # want 'X02'
)
x
# # A tibble: 3 × 3
# Placeholder `X01. Placeholder question text` `X02. Placeholder question text`
# <chr> <int> <int>
# 1 A 1 1
# 2 B 2 2
# 3 C 3 3
x |>
rename_with(
~str_extract(., "^.*(?=\\.)"), # get string between start and '.'
-Placeholder # ignore name with no question code in it
)
# # A tibble: 3 × 3
# Placeholder X01 X02
# <chr> <int> <int>
# 1 A 1 1
# 2 B 2 2
# 3 C 3 3
# 2. Rename from a lookup ------------------------------------------------
x <- mtcars[1:5, 1:5]
x
#> mpg cyl disp hp drat
#> Mazda RX4 21.0 6 160 110 3.90
#> Mazda RX4 Wag 21.0 6 160 110 3.90
#> Datsun 710 22.8 4 108 93 3.85
#> Hornet 4 Drive 21.4 6 258 110 3.08
#> Hornet Sportabout 18.7 8 360 175 3.15
cols_to_rename <- names(x)[-1]
cols_to_rename
#> [1] "cyl" "disp" "hp" "drat"
names_lookup <- data.frame(
old_names = cols_to_rename,
new_names = paste0(cols_to_rename, "_", LETTERS[1:4])
)
names_lookup
#> old_names new_names
#> 1 cyl cyl_A
#> 2 disp disp_B
#> 3 hp hp_C
#> 4 drat drat_D
x |>
rename_with(
~ names_lookup |> filter(old_names == .) |> pull(new_names),
all_of(cols_to_rename)
)
#> mpg cyl_A disp_B hp_C drat_D
#> Mazda RX4 21.0 6 160 110 3.90
#> Mazda RX4 Wag 21.0 6 160 110 3.90
#> Datsun 710 22.8 4 108 93 3.85
#> Hornet 4 Drive 21.4 6 258 110 3.08
#> Hornet Sportabout 18.7 8 360 175 3.15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment