如何在 R 数据框中合并因子变量的水平?
R 数据框可以包含数值型和因子型变量。已经发现,原始数据中的因子水平即使在不同的语言版本中也会被记录为同义词,但这并不常见。例如,一个因子变量可以有热和冷作为水平,但也有可能热被说印地语的人记录为 garam,因为 garam 是热的印地语形式。因此,我们需要将类似的水平合并为一个,这样我们就不需要为变量设置不必要的因子水平。
示例
考虑以下数据框 -
set.seed(109) x1<-rep(c("Sweet","Meetha","Bitter","Salty"),times=5) x2<-sample(1:100,20) x3<-rpois(20,5) df1<-data.frame(x1,x2,x3) df1
输出
x1 x2 x3 1 Sweet 8 4 2 Meetha 22 6 3 Bitter 25 3 4 Salty 85 10 5 Sweet 90 13 6 Meetha 10 0 7 Bitter 55 7 8 Salty 92 7 9 Sweet 95 4 10 Meetha 31 4 11 Bitter 5 4 12 Salty 56 6 13 Sweet 32 4 14 Meetha 78 6 15 Bitter 16 10 16 Salty 48 9 17 Sweet 49 4 18 Meetha 35 4 19 Bitter 37 9 20 Salty 11 8
由于 Meetha 是 Sweet 的印地语版本,我们可能希望将 Meetha 转换为 Sweet,这可以通过以下方式完成 -
示例
levels(df1$x1)[levels(df1$x1)=="Meetha"] <-"Sweet" df1
输出
x1 x2 x3 1 Sweet 8 4 2 Sweet 22 6 3 Bitter 25 3 4 Salty 85 10 5 Sweet 90 13 6 Sweet 10 0 7 Bitter 55 7 8 Salty 92 7 9 Sweet 95 4 10 Sweet 31 4 11 Bitter 5 4 12 Salty 56 6 13 Sweet 32 4 14 Sweet 78 6 15 Bitter 16 10 16 Salty 48 9 17 Sweet 49 4 18 Sweet 35 4 19 Bitter 37 9 20 Salty 11 8
让我们看另一个例子 -
示例
ID <-1:20 Class<-rep(c("First","Second","Third","Fourth","One"),each=4) df2<-data.frame(ID,Class) df2
输出
ID Class 1 1 First 2 2 First 3 3 First 4 4 First 5 5 Second 6 6 Second 7 7 Second 8 8 Second 9 9 Third 10 10 Third 11 11 Third 12 12 Third 13 13 Fourth 14 14 Fourth 15 15 Fourth 16 16 Fourth 17 17 One 18 18 One 19 19 One 20 20 One
示例
levels(df2$Class)[levels(df2$Class)=="One"] <-"First" df2
输出
ID Class 1 1 First 2 2 First 3 3 First 4 4 First 5 5 Second 6 6 Second 7 7 Second 8 8 Second 9 9 Third 10 10 Third 11 11 Third 12 12 Third 13 13 Fourth 14 14 Fourth 15 15 Fourth 16 16 Fourth 17 17 First 18 18 First 19 19 First 20 20 First
广告