如何在R数据帧中组合因子变量的级别?
R数据框可以具有数字变量以及因子变量。可以看出,即使在不同的语言版本中,原始数据中的因子水平也被记录为同义词,但这很少见。例如,因子变量可以具有热和冷的水平,但是由于garam是hot的北印度语形式,hot可能被印地语母语者记录为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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语