-2

以下代码中boxplot第一个参数中的公式如何在a重新排序后使b和a之间正确对应。

a <- as.factor(c("TX", "NY", "WA"))
levels(a)
b <- c(5, 3, 2)
boxplot(b ~ a)
# Order the levels of a according to their value in b
a_reordered <- reorder(a, b)
levels(a_reordered)
boxplot(b ~ a_reordered)

为什么 b 也不需要重新排序?

编辑:我用@Marius的具体例子替换了我的例子

4

1 回答 1

4

在您的boxplot(quantity ~ bymedian)通话中,x 轴上的状态顺序由bymedian因子的级别顺序决定。比较levels(x$State)levels(bymedian)您会明白为什么这两个变量在绘图中使用时表现不同。请注意,数据本身bymedian并没有改变顺序。

一个简单的例子:

a <- as.factor(c("TX", "NY", "WA"))
levels(a)
b <- c(5, 3, 2)
boxplot(b ~ a)
# Order the levels of a according to their value in b
a_reordered <- reorder(a, b)
levels(a_reordered)
boxplot(b ~ a_reordered)

为了清楚说明实际数据没有改变是什么意思:

> a
[1] TX NY WA
Levels: NY TX WA
> a_reordered
[1] TX NY WA
# Don't be confused by this extra attr(, "scores") bit: the line
# above is the actual data stored in the vector
#attr(,"scores")
#NY TX WA 
# 3  5  2 
Levels: WA NY TX
> b
[1] 5 3 2
于 2013-01-21T00:24:49.437 回答