簡體   English   中英

一個因子如何在R中自動排序它的水平?

[英]How does a factor order it's levels automaticly in R?

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嗎?

你將f2設置為c("x", "e", "t")因此,因子3 (從字母順序)仍然處於第一位置的“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有3個級別的因子(3個不同的值),它們按順序為“e”,“t”,“x”,所以“e”被編碼為因子1,“t”被編碼為因子2和“x”被編碼為因子3

  • f2包含3個編碼值f2

去分解:

  • 取第1個編碼值(3),並將其替換為其級別(“x”=因子3),
  • 然后是第二個編碼值(1),並將其替換為其級別(“e”=因子1),

...

  • 然后是最后一個編碼值(2),並將其替換為其級別(“t”=因子2)

=>你得到“x”,“e”,“t”。

讓我們在f2的末尾添加一個額外的值(“e”)

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

您可以看到編碼“e”的因子1現在位於第4位。

f2現在代表:“x”,“e”,“t”,“e”。

str(f2)按字母順序顯示字母,但數字取決於f2對象中字母占用的位置。

如果f2是xet

 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

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM