简体   繁体   中英

How to recode a set of variables in a dataframe in R

I have a dataframe with different variables containing values from 1 to 5. I want to recode some variables in the way that 5 becomes 1 and vice versa (x=6-x). I want to define a list of variables, that will be recoded like this in my dataframe.

Here is my approach using lapply . I haven't really understood it yet.

  #generate example-dataset
    var1<-sample(1:5,100,rep=TRUE)
    var2<-sample(1:5,100,rep=TRUE)
    var3<-sample(1:5,100,rep=TRUE)
    dat<-as.data.frame(cbind(var1,var2,var3))

    recode.list<-c("var1","var3")  
    recode.function<- function(x){          
    x=6-x
     }
    lapply(recode.list,recode.function,data=dat)

There's no need for an external function or for a package for this. Just use an anonymous function in lapply , like this:

df[recode.list] <- lapply(df[recode.list], function(x) 6-x)

Using [] lets us replace just those columns directly in the original dataset. This is needed since just using lapply would result in the data as a named list .


As noted in the comments, you can actually even skip lapply :

df[recode.list] <- 6 - df[recode.list] 

Here's an option to do this with dplyr :

recode.function<- function(x){          
  x <- 6-x 
}

recode.list <- c("var1","var3") 

require(dplyr)
df %>% mutate_each_(funs(recode.function), recode.list)

#    var1 var2 var3
#1      2    2    4
#2      3    3    3
#3      3    5    2
#4      3    3    2
#5      4    3    3
#6      5    4    1
#...

You can use mapvalues from plyr .

require(plyr)
# if you just want to replace 5 with 1 and vice versa
df[, recode.list] <- sapply(df[, recode.list], mapvalues, c(1, 5), c(5,1))
# if you want to apply to x=6-x to all values (in this case you don't need mapvalues)
df[, recode.list] <- sapply(df[, recode.list], mapvalues, 1:5, 5: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