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:Using
[]
lets us replace just those columns directly in the original dataset. This is needed since just usinglapply
would result in the data as a namedlist
.As noted in the comments, you can actually even skip
lapply
: