如何将 R 数据框列中的代码“是”更改为 1?
要将代码“Yes”更改为1,我们可以使用ifelse函数并将Yes设置为1,其他设置为0。例如,如果我们有一个名为df的数据框,其中包含一个字符列x,该列具有Yes和No值然后我们可以使用ifelse(df$x=="Yes",1,0)命令将这些值转换为1和0。
示例1
考虑以下数据框-
Agree<-sample(c("Yes","No"),20,replace=TRUE) x<-rpois(20,5) df1<-data.frame(Agree,x) df1输出结果
Agree x 1 No 6 2 No 4 3 Yes 5 4 No 9 5 No 4 6 No 0 7 Yes 4 8 No 5 9 No 6 10 No 5 11 No 6 12 No 2 13 No 6 14 No 2 15 Yes 3 16 Yes 9 17 No 3 18 Yes 3 19 No 0 20 Yes 7
在df1中将Yes转换为1并将No转换为0-
df1$Agree<-ifelse(df1$Agree=="Yes",1,0) df1
Agree x 1 0 6 2 0 4 3 1 5 4 0 9 5 0 4 6 0 0 7 1 4 8 0 5 9 0 6 10 0 5 11 0 6 12 0 2 13 0 6 14 0 2 15 1 3 16 1 9 17 0 3 18 1 3 19 0 0 20 1 7
例2
Approved<-sample(c("Yes","No"),20,replace=TRUE) y<-rnorm(20,30,2.4) df2<-data.frame(Approved,y) df2输出结果
Approved y 1 Yes 33.17910 2 No 31.69268 3 Yes 30.96484 4 Yes 34.12339 5 Yes 30.84079 6 No 27.57933 7 Yes 29.13050 8 No 32.55457 9 Yes 34.39399 10 No 30.22306 11 Yes 29.65322 12 Yes 29.42060 13 Yes 30.75312 14 No 32.25545 15 Yes 27.54001 16 No 25.93290 17 No 27.45960 18 Yes 26.28884 19 No 32.08387 20 Yes 28.60269
在df2中将Yes转换为1并将No转换为0-
df2$Approved<-ifelse(df2$Approved=="Yes",1,0) df2
Approved y 1 1 33.17910 2 0 31.69268 3 1 30.96484 4 1 34.12339 5 1 30.84079 6 0 27.57933 7 1 29.13050 8 0 32.55457 9 1 34.39399 10 0 30.22306 11 1 29.65322 12 1 29.42060 13 1 30.75312 14 0 32.25545 15 1 27.54001 16 0 25.93290 17 0 27.45960 18 1 26.28884 19 0 32.08387 20 1 28.60269