如何在R中的数据框中重新编码一组变量

SEM*_*son 1 reverse r lapply recode

我有一个数据框,其中包含从1到5的不同变量.我想以5变为1的方式重新编码一些变量,反之亦然(x = 6-x).我想定义一个变量列表,这些变量将在我的数据帧中像这样重新编码.

这是我使用的方法lapply.我还没有真正了解它.

  #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)
Run Code Online (Sandbox Code Playgroud)

A5C*_*2T1 6

不需要外部功能或包装.只需使用匿名函数lapply,如下所示:

df[recode.list] <- lapply(df[recode.list], function(x) 6-x)
Run Code Online (Sandbox Code Playgroud)

使用[]让我们直接在原始数据集中替换那些列.这是必需的,因为只使用lapply会导致数据作为命名list.


如评论中所述,您甚至可以跳过lapply:

df[recode.list] <- 6 - df[recode.list] 
Run Code Online (Sandbox Code Playgroud)