dfres5
dfres5

Reputation: 11

I want to revalue multiple variables at the same time in R

For my thesis research I am trying to revalue multiple variables/columns at the same time. I have tried using the following function, but this would require me to specify each column apart:

full_df$CR39 <- revalue(full_df$CR39, c("1"="0", "2" ="1"))

I have got around 65 variables (named CR00, CR01, CR02, ...) that I want to recode. The value "1" must become "0" and the value "2" must become "1." I also have got variables named CR00FAM, CR01FAM, CR02FAM, ...) which I do not wish to revalue at the same time.

I have tried using the 'select' function, but this does not seem to help: full_df%>% select(starts_with("DF"), -contains("FAM")).

Does anyone know a possible solution? I have searched a lot of stackoverflow topics, but none of the proposed solutions worked out for me.

Upvotes: 1

Views: 434

Answers (1)

akrun
akrun

Reputation: 887028

We can loop over the variables and do this. Select the columns of interest based on a regex i.e. those column names starts with (^) the 'CR' followed by one or more digits (\\d+) at the end ($) of the string. Loop over the selected columns with lapply and apply revalue, assign the output back to the selected columns dataset

nm1 <- grep("^CR\\d+$", names(full_df), value = TRUE)
full_df[nm1] <- lapply(full_df[nm1], function(x) revalue(x, c("1"="0", "2" ="1"))

Or using dplyr

library(dplyr)
full_df <- full_df %>%
    mutate(across(matches("^CR\\d+$"), ~ 
         revalue(., c("1" = "0", "2" = "1"))))

Upvotes: 0

Related Questions