如何在R中使用dplyr包的mutate函数为因子变量创建具有更改后的因子水平的新列?
我们知道因子变量有很多水平,但我们拥有的因子水平可能并非我们需要的形式。例如,如果我们想要大写字母作为因子水平,但原始数据使用的是小写英文字母。在这种情况下,我们可以使用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
广告