如何使用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
重命名City变量的水平:
示例
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
广告