在R中以我自己的方式排序变量

时间:2010-07-20 11:57:43

标签: r sorting

我想以自己的方式对分类变量进行排序。我已将数据集分组为“1-5”,“6-10”,“11-20”......“> 251”等类别。如果绘制变量或将它们显示在表格中,则图例序列中的序列分别为“混乱”。

这并不奇怪,因为R不知道这些无序变量实际上是有序的。有没有办法将手动定义的序列附加到它们?

对于任何提前建议,请等等!

3 个答案:

答案 0 :(得分:4)

分类变量在绘制时存储为(或转换为)factor。它们在图中出现的顺序取决于因子的水平。

您可能希望使用cut来创建群组。 e.g。

dfr <- data.frame(x = runif(100, 1, 256))
dfr$groups <- cut(dfr$x, seq(1, 256, 5))

此问题与another recent SO question非常相似。

答案 1 :(得分:4)

当我想手动为一个因子指定不同的顺序(繁琐但有时必要)时,我就是这样做的:

> ## a factor
> x <- factor(letters[1:3])
> ## write out levels with dput
> dput(levels(x))
c("a", "b", "c")
> ## copy, paste, modify and use factor again. e.g.
> x <- factor(x, levels=c("b", "a", "c"))
> x
[1] a b c
Levels: b a c

答案 2 :(得分:-1)

我喜欢使用split来做这件事。

  

vect = runif(10)

     

vect.categories = c(rep(LETTERS [1],5),rep(LETTERS [2],3),rep(LETTERS [5],2))

     

category.list = split(vect,vect.categories)

     

...

可能没有关系,但我想我会提出建议。