简体   繁体   中英

recoding many variables in a same way, using mutate_at and list with dplyr

I've got 20 variables (V1, V2, ...) coded "Y" or "N". I want to recode them "1" or "2" with variable names like this "R_V1", "R_V2".

Thanks for a solution.

You could use mutate_all and recode :

library(dplyr)
df %>% mutate_all(list(R = ~recode(., Y = 1, N = 2)))

Or in base R we can use lapply :

df[paste0('R_', names(df))] <- lapply(df, function(x) ifelse(x == 'Y', 1, 2))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM