我们知道一个因子变量有很多级别,但是我们拥有的因子级别可能没有按照需要的形式出现。例如,如果我们要使用大写字母作为要素级别,但是原始数据中的英文字母是小写字母。在这种情况下,我们可以使用dplyr包的mutate转换那些因子水平。
请看以下数据帧-
x <-letters[1:20] y <-20:1 df <-data.frame(x,y) str(df) 'data.frame': 20 obs. of 2 variables: $ x: Factor w/ 20 levels "a","b","c","d",..: 1 2 3 4 5 6 7 8 9 10 ... $ y: int 20 19 18 17 16 15 14 13 12 11 ... df
输出结果
x y 1 a 20 2 b 19 3 c 18 4 d 17 5 e 16 6 f 15 7 g 14 8 h 13 9 i 12 10 j 11 11 k 10 12 l 9 13 m 8 14 n 7 15 o 6 16 p 5 17 q 4 18 r 3 19 s 2 20 t 1
创建具有更改级别的新列-
df%>% mutate(x,levels=LETTERS[1:20])
输出结果
x y levels 1 a 20 A 2 b 19 B 3 c 18 C 4 d 17 D 5 e 16 E 6 f 15 F 7 g 14 G 8 h 13 H 9 i 12 I 10 j 11 J 11 k 10 K 12 l 9 L 13 m 8 M 14 n 7 N 15 o 6 O 16 p 5 P 17 q 4 Q 18 r 3 R 19 s 2 S 20 t 1 T
让我们看另一个例子-
F <-rep(c("Cold","Hot","Sweet","Bitter"),times=5) Count <-sample(1:50,20) Taste <-data.frame(F,Count) Taste
输出结果
F Count 1 Cold 49 2 Hot 18 3 Sweet 28 4 Bitter 9 5 Cold 29 6 Hot 13 7 Sweet 39 8 Bitter 30 9 Cold 11 10 Hot 5 11 Sweet 45 12 Bitter 31 13 Cold 36 14 Hot 41 15 Sweet 44 16 Bitter 15 17 Cold 20 18 Hot 48 19 Sweet 8 20 Bitter 43
Taste%>% mutate(F,levels=rep(c("Very Cold","Very Hot","Very Sweet","Very Bitter"),times=5))
输出结果
F Count levels 1 Cold 49 Very Cold 2 Hot 18 Very Hot 3 Sweet 28 Very Sweet 4 Bitter 9 Very Bitter 5 Cold 29 Very Cold 6 Hot 13 Very Hot 7 Sweet 39 Very Sweet 8 Bitter 30 Very Bitter 9 Cold 11 Very Cold 10 Hot 5 Very Hot 11 Sweet 45 Very Sweet 12 Bitter 31 Very Bitter 13 Cold 36 Very Cold 14 Hot 41 Very Hot 15 Sweet 44 Very Sweet 16 Bitter 15 Very Bitter 17 Cold 20 Very Cold 18 Hot 48 Very Hot 19 Sweet 8 Very Sweet 20 Bitter 43 Very Bitter