为什么因子变量不在R中重新排序

时间:2014-07-27 12:40:19

标签: r

我正在使用此页面中的示例:http://kohske.wordpress.com/2010/12/29/faq-how-to-order-the-factor-variables-in-ggplot2/但代码似乎不起作用:

d <- data.frame(Team1=c("Cowboys", "Giants", "Eagles", "Redskins"), Win=c(20, 13, 9, 12))
d
     Team1 Win
1  Cowboys  20
2   Giants  13
3   Eagles   9
4 Redskins  12
> 
d$Team1
[1] Cowboys  Giants   Eagles   Redskins
Levels: Cowboys Eagles Giants Redskins
> 
> 
d$Team3 <- reorder(d$Team1, d$Win)
d
     Team1 Win    Team3
1  Cowboys  20  Cowboys
2   Giants  13   Giants
3   Eagles   9   Eagles
4 Redskins  12 Redskins
> 
> 
d$Team3
[1] Cowboys  Giants   Eagles   Redskins
Levels: Cowboys Eagles Giants Redskins
> 
> 
d[order(d$Team1),]
     Team1 Win    Team3
1  Cowboys  20  Cowboys
3   Eagles   9   Eagles
2   Giants  13   Giants
4 Redskins  12 Redskins
> 
d[order(d$Team3),]
     Team1 Win    Team3
1  Cowboys  20  Cowboys
3   Eagles   9   Eagles
2   Giants  13   Giants
4 Redskins  12 Redskins
> 

尽管有reoder命令,但Team3列与Team1相同。问题出在哪儿。谢谢你的帮助。

编辑:

levels(d$Team1)
[1] "Cowboys"  "Eagles"   "Giants"   "Redskins"
> 
levels(d$Team3)
[1] "Cowboys"  "Eagles"   "Giants"   "Redskins"
> 

1 个答案:

答案 0 :(得分:0)

函数reorder更改级别的顺序,而不是值的顺序:

> levels(d$Team1)
[1] "Cowboys"  "Eagles"   "Giants"   "Redskins"
> levels(d$Team3)
[1] "Eagles"   "Redskins" "Giants"   "Cowboys"