简体   繁体   中英

R: how to do recode for multiple variables at a time

I am trying not to get tangled in loops and complicated code that will take a lot longer to get right than simply repeating lines of code.

I want to do the following recode for multiple variables in R. I concatenated the variables, but they didn't change the content of the original data file.

recode(d$var1,"1=50; 2=70; 3=100; 4=140; 5=190")

repeat for d$var2 to d$var20 ....

If it's better use of coding time to copy the code 20 times, just tell me!

Many thanks.

Let

d = data.frame(var1 = c(1, 2, 3, 4, 5), 
               var2 = c(1, 2, 3, 4, 5), 
               var3 = c(1, 2, 3, 4, 5))

Then with a simple apply we get

A = apply(d, 
          2, 
         function(x) dplyr::recode(x, "1" = "50", "2" = "70", 
                                       "3" = "100" , "4" = "140", 
                                       "5" = "190")) %>% 
    as.data.frame(stringsAsFactors = FALSE)

the output

> A
  var1 var2 var3
1   50   50   50
2   70   70   70
3  100  100  100
4  140  140  140
5  190  190  190

If all of your variables are in the same dataframe, you can edit var1:var3 with var1:var999 to recode all of the variables.

With dplyr :

A <- d %>%
  mutate_at(vars(var1:var3), .funs = list(
    ~case_when(
      . == 1 ~ 50,
      . == 2 ~ 70,
      . == 3 ~ 100,
      . == 4 ~ 140,
      . == 5 ~ 190
    )
  ))

If you have var1:var3 across multiple dataframes or lists, you could create a function such as:

recode_func <- function(x) {

df <- df %>%
  mutate_at(vars(x), .funs = list(
    ~case_when(
      . == 1 ~ 50,
      . == 2 ~ 70,
      . == 3 ~ 100,
      . == 4 ~ 140,
      . == 5 ~ 190
    )
  ))
}

And then call the function to a dataframe or list.

Gives us:

  var1 var2 var3
1   50   50   50
2   70   70   70
3  100  100  100
4  140  140  140
5  190  190  190

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