[英]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
去分解:
...
=>你得到“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.