R中如何自动排序因子的水平?

3
f1 <- c("a", "b", "c")

f2 <- c("x", "e", "t")

f1 <-factor(f1)

f1
#[1] a b c
#Levels: a b c


str(f1)
#Factor w/ 3 levels "a","b","c": 1 2 3

f2 <-factor(f2)

f2
#[1] x e t
#Levels: e t x

str(f2)
#Factor w/ 3 levels "e","t","x": 3 1 2

正如上面提到的,为什么在 f2"e" 被视为 3?按字母顺序考虑,它不应该是 1 吗?

“e” 被编码为 1。你误解了 str 的输出。 - Hong Ooi
没问题,我现在明白了。 - Cenk
2个回答

6
您将f2设置为c("x", "e", "t"),因此字母表顺序中的第三个因子"X"仍处于第一位置,而在第二位置的"e"实际上具有因子1
    f2 <- factor(c("x", "e", "t"))
    str(f2)
    Factor w/ 3 levels "e","t","x": 3 1 2

str(f2)的结果说明:

  • f2是因子类型,这意味着值不能直接使用,而是编码为因子

  • f2有三个因子级别(三个不同的值),它们按顺序为"e"、"t"、"x",所以"e"被编码为因子1,"t"被编码为因子2,"x"被编码为因子3。

  • f2包含三个编码值3、1、2。

去编码化:

  • 取第一个编码值(3),并将其替换为其级别("x"=因子3),
  • 然后是第二个编码值(1),将其替换为其级别("e"=因子1),

...

  • 然后是最后一个编码值(2),将其替换为其级别("t"=因子2)

=> 你会得到"x"、"e"、"t"。

让我们在f2末尾添加一个额外的值("e" again)。

    f2[4] <-  "e"
    str(f2)
    Factor w/ 3 levels "e","t","x": 3 1 2 1

您可以看到,因子1现在对应于字母"e"的编码位于第4个位置。

f2 现在表示:"x","e","t","e"。


正如你所说,“e”在第二个位置,但在我的例子中,“e”被分解为“3”,而不是(实际上的)“1”或“2”? - Cenk

1

str(f2)会按字母顺序显示字母,但数字是根据f2对象中字母所占的位置排序的。

如果f2是x e t

 Levels are e t x (in order)

 Numbers for the above letters would be: (in order)

 e = 1
 t = 2
 x = 3

 str gives number sequence according to the place occupied by the letters in     
 the original f2 object , i.e. x, e, t = 3,1,2

希望这有所帮助。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接