Skip to content

Instantly share code, notes, and snippets.

@jrosell
Last active March 9, 2022 10:20
Show Gist options
  • Save jrosell/f50a0a785606c6db30f1c1ee6c1521be to your computer and use it in GitHub Desktop.
Save jrosell/f50a0a785606c6db30f1c1ee6c1521be to your computer and use it in GitHub Desktop.
# Load libraries
library(tidyverse)
# Original names
df <- tibble(Q1=c(1), Q2=c(1), Q3=c(1), Q4=c(1), Q5=c(1), Q6=c(1), Q7=c(1), Q25_1=c(1), Q25_2=c(1), Q25_3=c(1), Q25_4=c(1), Q25_5=c(1), Q25_6=c(1), Q25_7=c(1), Q25_8=c(1), Q25_9=c(1), Q25_10=c(1), Q25_11=c(1), Q25_12=c(1), Q25_13=c(1), Q25_14=c(1), Q25_15=c(1), Q25_16=c(1), Q26_1=c(1), Q26_2=c(1), Q26_3=c(1), Q26_4=c(1), Q26_5=c(1), Q26_6=c(1), Q26_7=c(1))
df %>% glimpse()
# Option A) Using select and rename_with
df %>%
select(
English = Q1,
Familiar_CSD = Q2,
Familiar_CSD_2 = Q3,
Age = Q4,
Gender = Q5,
Race = Q6,
Ethnicity = Q7,
starts_with("Q25_"),
starts_with("Q26_")
) %>%
rename_with(~ str_replace(., "^Q25_(\\d+)", "LC\\1_dys")) %>%
rename_with(~ str_replace(., "^Q26_(\\d+)", "S\\1_dys")) %>%
glimpse()
# Option B) Using character vector and set_names
nicer <- c(
"English",
"Familiar_CSD",
"Familiar_CSD_2",
"Age",
"Gender",
"Race",
"Ethnicity",
c(paste0("LC",1:16,"_dys")),
c(paste0("S",1:7,"_dys"))
)
df %>%
set_names(nicer) %>%
glimpse()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment