I am working with some survey data where some of the responses have been coded inconsistently. For instance' "I don't know" may be coded as 4, 5, 97, or 777. I want to standardize all of these responses as "77" as efficiently as possible. I would like to use a crosswalk and want to avoid creating a new recode command for every variable in which this occurs, if possible, since there are several.
library(tidyverse)
#df with the inconsistent fourth category
var1 <- c("1", "2", "3", "4")
var2 <- c("1", "2", "3", "5")
var3 <- c("1", "2", "3", "97")
var4 <- c("1", "2", "3", "777")
df <- data.frame(var1, var2, var3, var4)
var <- c("var1", "var2", "var3", "var4")
oldvalue <- c("4", "6", "97", "777")
newvalue <- c("77", "77", "77", "77")
#crosswalk of old values to new values
cw <- data.frame(var, oldvalue, newvalue)
recodevars = cw$var
A few things I have tried are as follows, although I haven't had any luck with any. Please let me know if you have any suggestions.
rec_all = df %>%
transmute_at(vars(recodevars), funs(recode(., cw$oldvalue = cw$newvalue)))
for(i in recodevars){
rec_all = df %>%
transmute_at(vars(recodevars), funs(ifelse(i == cw$oldval, cw$newval, i)))
}