I am working with PUMS data and I am using tidycensus to translate the values of certain columns. However, this adds a new column with structure: columnname_label. I want to use mutate to replace the original column with the new translated values in columnname_label. Here is example of my data frame:
df <-data.frame(Region= c(1,2,1,4,3,1),
Region_label = c("North", "South", "North", "West", "East", "North"),
Broadband = c(0,1,0,0,0,1)
Broadband_label = c("No","Yes","No","No","No","Yes")
Hispeed = c(1,1,0,0,1,0)
Hispeed_label = c("Yes", "Yes","No","No","Yes","No")
I know I can write out code like this using tidycensus:
library(tidyverse)
recode <- df %>% mutate(Region = Region_label) %>% mutate(Broadband = Broadband_label) %>%
mutate(Hispeed = Hispeed_label)
However, I have 66 columns that need to be matched to the "_label" columns. Is there a more elegant way to perform this instead of writing 66 mutate statements?
I have tried writing a loop using mutate_at, but it does not work.
subset1 <- grep('*label*',names(df),value = TRUE)
name <- names(df)
for (i in subset1) {
final <- final_house %>% mutate_at(vars(matches(trimws(name,"right","\\_label"))),i)
}
This does not work.
Thank you!