2014-09-24 31 views
0

我試圖將數據框(p2)中的一個因子(tickets_other)轉換爲整數。繼將R幫助指導,以及來自其他其他方面的建議,該代碼應工作:將因子強制轉換爲整數的問題

as.numeric(levels(p2$tickets_other))[p2$tickets_other] 

列不包含港定居,所以我得到一個警告:

Warning message: 
NAs introduced by coercion 

這很好,但是它強迫爲數字後,它仍然讀取的一個因素:(as.character())

class(p2$tickets_other) 
[1] "factor" 

如果我使用as.numeric同樣的結果發生了:

as.numeric(as.character(p2$tickets_other)) 
Warning message: 
NAs introduced by coercion 
class(p2$tickets_other) 
[1] "factor" 
+0

請提供一些數據 – 2014-09-24 17:31:42

+0

這裏命令'head(p2)'或'head(p2 $ tickets_other)'的輸出結果。 – rnso 2014-09-24 17:34:37

+0

不看你的數據。我猜你需要'as.numeric(as.character(p2 $ tickets_other))' – Vlo 2014-09-24 17:53:30

回答

0

我修復了這個問題。這其實很簡單。命令:

as.numeric(levels(p2$tickets_other))[p2$tickets_other] 

是正確的,但我沒能存儲結果:

p2$tickets_other <- as.numeric(levels(p2$tickets_other))[p2$tickets_other] 

簡單的錯誤,它回顧。感謝DMT的建議。

0

你這樣做:

as.numeric(levels(p2$tickets_other))[p2$tickets_other] 

您正在閱讀從p2$tickets_other(載體)的水平,然後將其轉換爲數字(仍然是一個向量),然後根據訪問該矢量的索引值在p2$tickets_other

我無法想象這是你真正想要做的。

也許只是

as.numeric(p2$tickets_other) 

是你想要的嗎?