如何在R中使用dplyr包的mutate重命名因子变量的因子水平?
我们知道一个因子变量有很多级别,但是我们拥有的因子级别可能没有按照需要的形式出现。例如,如果我们要使用大写字母作为要素级别,但是原始数据具有小写英文字母。在这种情况下,我们可以使用dplyr软件包的mutate重命名那些因子级别。
示例
请看以下数据帧-
City <-rep(c("LA","NY","SF","LV"),each=5) Temp <-sample(1:50,20) df1 <-data.frame(City,Temp) df1
输出结果
City Temp 1 LA 2 2 LA 47 3 LA 7 4 LA 24 5 LA 11 6 NY 50 7 NY 9 8 NY 46 9 NY 18 10 NY 13 11 SF 37 12 SF 12 13 SF 8 14 SF 3 15 SF 19 16 LV 28 17 LV 20 18 LV 43 19 LV 1 20 LV 22
重命名城市变量的级别-
示例
df1%>%mutate(City=recode(City,LA="Los Angeles",NY="New York",SF="San Francisco",LV="Las Vegas"))
输出结果
City Temp 1 Los Angeles 2 2 Los Angeles 47 3 Los Angeles 7 4 Los Angeles 24 5 Los Angeles 11 6 New York 50 7 New York 9 8 New York 46 9 New York 18 10 New York 13 11 San Francisco 37 12 San Francisco 12 13 San Francisco 8 14 San Francisco 3 15 San Francisco 19 16 Las Vegas 28 17 Las Vegas 20 18 Las Vegas 43 19 Las Vegas 1 20 Las Vegas 22
让我们看另一个例子-
示例
Grade <-rep(c("A","B","C","D","E"),times=4) Score <-c(91:94,81:84,61:64,51:54,26:29) df2 <-data.frame(Grade,Score) df2
输出结果
Grade Score 1 A 91 2 B 92 3 C 93 4 D 94 5 E 81 6 A 82 7 B 83 8 C 84 9 D 61 10 E 62 11 A 63 12 B 64 13 C 51 14 D 52 15 E 53 16 A 54 17 B 26 18 C 27 19 D 28 20 E 29
示例
df2%>%mutate(Grade=recode(Grade,A="Excellent",B="Very Good",C="Good",D="Bad",E="Very Bad"))
输出结果
Grade Score 1 Excellent 91 2 Very Good 92 3 Good 93 4 Bad 94 5 Very Bad 81 6 Excellent 82 7 Very Good 83 8 Good 84 9 Bad 61 10 Very Bad 62 11 Excellent 63 12 Very Good 64 13 Good 51 14 Bad 52 15 Very Bad 53 16 Excellent 54 17 Very Good 26 18 Good 27 19 Bad 28 20 Very Bad 29