2014-10-09 98 views
0

我試圖將R中的因子值轉換爲數值。我嘗試了各種方法,但不管我做什麼,我都會收到錯誤「由強制引入的NAs」。這裏是我運行的示例代碼和我得到的錯誤:在r中將因子值轉換爲數值

> demand <- read.csv("file.csv") 
> demand[3,3] 
[1] 5,185 
25 Levels: 2/Jan/2011 3,370 4,339 4,465 4,549 4,676 4,767 4,844 5,055 5,139 5,185 5,265 5,350 5,434 ... dam 

> a <- demand[3,3] 
> as.numeric(as.character(a)) 
[1] NA 
Warning message: 
NAs introduced by coercion 

如何獲取數值?

+2

你在你的號碼中有逗號,你似乎也有一個日期。你可以用gsub去掉逗號,但是這對你的第一個值沒有幫助(你是否應該在你的文件中跳過一行?) – mnel 2014-10-09 03:52:19

+0

請給出你的數據框的10個觀察結果,並使其成爲一個可重現的例子。 – technOslerphile 2014-10-09 04:00:25

回答

2

此時應更換

as.numeric(as.character(a)) 

在你的代碼

as.numeric(gsub("[,]", "", as.character(a))) 
0

我有2條評論點擊這裏:

  1. 您使用的可能是從東歐Excel中浮動符號文件(」 ,' 代替 '。')。

爲了使其運行良好,請使用read.csv2()函數。

  1. 第一次觀察可能是頭部?我想下面的觀察結果是通過這個日期(2/Jan/2011)連接起來的。我會建議使用header=T參數。

彙總:

嘗試read.csv2("file.csv", head=T)

如果你仍然需要改變的因素,以數值的任何原因,我建議:

f = as.factor(1:10)

as.numeric(f[f])

最佳, Adii_