[英]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). 我有一个数据框,其中的变量包含从1到5的值。我想重新编码一些变量,使5变为1,反之亦然(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
. 这是我使用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: 只需在lapply
使用匿名函数,如下所示:
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
. 这是必需的,因为仅使用lapply
会导致数据作为命名list
。
As noted in the comments, you can actually even skip lapply
: 如评论中所述,您实际上甚lapply
可以跳过lapply
:
df[recode.list] <- 6 - df[recode.list]
Here's an option to do this with dplyr
: 这是使用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
. 您可以使用mapvalues
的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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.