简体   繁体   中英

recode variable in loop R

im trying to recode a lot of variables (more than 53) in a loop, but it won't work. can someone please tell me, where my mistake is?

i give you a small exaple

data <-  read.csv("test.csv", header = TRUE, ";", na = -77)

data$var1 <- recode(data$var1, "1=0; 2=1; 3=2; 4=3; NA=NA")

here i have var 1-59 and several items that must be recoded in a different way.

i tried

for (i in 1:59){
get(paste0(data$var",i)) <- recode(paste0("data$var",i), "1=0; 2=1; 3=2; 4=3; NA=NA"
}

and

for (i in c(65, 73, 99){
get(paste0(data$var",i)) <- recode(paste0("data$var",i), "1=0; 2=0; 3=0; 4=1; NA=NA"
}

The Code will not work. Wheres my mistake? Can someone please give me a hind?

Thank you very much :) derlu

You can use switch function to recode values and data.table to recode values in all columns in one go:

library(data.table)    

# function to recode values
myfun <- function(val){
    if(is.na(val)) return (NA)
    else switch(val, '1'= '0','2' = '1', '3'='2','4'='3')
}

# apply the function to the selected columns
col_names <- paste0('var', 1:59)
df[,(col_names) := lapply(.SD, function(x) unlist(sapply(x, myfun)) ), .SDcols = col_names]

print(df)

How about a more readable tidyverse solution?

library(dplyr)
library(magrittr)

data %<>% 
  mutate_at(c(1:59)    , recode, '1'='0', '2'='1', '3'='2', '4'='3') %>%
  mutate_at(c(65,73,99), recode, '1'='0', '2'='0', '3'='0', '4'='1')

If you prefer, you can also use character vectors as the first argument that you pass to mutate_at . Like so:

data %<>% 
  mutate_at(paste0('var', c(1:59))    , recode, '1'='0', '2'='1', '3'='2', '4'='3') %>%
  mutate_at(paste0('var', c(65,73,99)), recode, '1'='0', '2'='0', '3'='0', '4'='1')

The third option (not applicable in this case because there are too many columns) is to use vars :

data %>% 
  mutate_at(vars(var65, var73, var99), recode, '1'='0', '2'='0', '3'='0', '4'='1')

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