2016-03-11 24 views
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,當它按字母順序考慮時?一個因子如何在R中自動排列它的水平?

+0

''e「'編碼爲1.您誤解了'str'輸出。 –

+0

沒關係。我現在明白了。 – Cenk

回答

6

您設置f2作爲c("x", "e", "t")因此「X」,這是因子3(從字母順序)仍處於第一位置,而「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 「×」 被編碼爲因子3

  • f2含有3個編碼的值3,1,2

要取消比化:

  • 取第一編碼值(3 ),並將其替換爲其級別(「 X 「=因子3),
  • 則第二編碼值(1),並通過它的電平(代替它的」 e「=因子1),

...

  • 然後最後的編碼值(2),並將其替換爲它的等級(「t」=因子2)

=>您將得到「x」,「e」,「t」。

讓我們在f2

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

末可以看到,因子1編碼的「E」現在是在第4的位置添加一個額外的值(「E」再次)。

f2現在表示:「x」,「e」,「t」,「e」。

+0

正如你所說的「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 

希望這有助於。