2012-06-22 47 views
9

我有一個數字向量(future_prices)在我的情況。我使用另一個向量(此處爲:pred_commodity_prices $ futuredays)的日期向量來創建月份的數字。之後,我使用cbind將月份綁定到數字向量。但是,發生的情況是數字矢量變爲非數字。你知道這是什麼原因嗎?當我使用as.numeric(future_prices)時,我會得到奇怪的值。有什麼可以替代的?謝謝R:數字向量在日期後變成非數字

head(future_prices) 
pred_peak_month_3a pred_peak_quarter_3a 
1   68.33907    62.37888 
2   68.08553    62.32658 

is.numeric(future_prices) 
[1] TRUE 
> month = format(as.POSIXlt.date(pred_commodity_prices$futuredays), "%m") 
> future_prices <- cbind (future_prices, month) 
> head(future_prices) 
    pred_peak_month_3a  pred_peak_quarter_3a month 
    1 "68.3390747063745" "62.3788824938719"  "01" 
is.numeric(future_prices) 
[1] FALSE 

回答

21

原因是cbind返回一個矩陣,而一個矩陣只能保存一種數據類型。您可以使用data.frame代替:

n <- 1:10 
b <- LETTERS[1:10] 
m <- cbind(n,b) 
str(m) 
chr [1:10, 1:2] "1" "2" "3" "4" "5" "6" "7" "8" "9" ... 
- attr(*, "dimnames")=List of 2 
    ..$ : NULL 
    ..$ : chr [1:2] "n" "b" 

d <- data.frame(n,b) 
str(d) 
'data.frame': 10 obs. of 2 variables: 
$ n: int 1 2 3 4 5 6 7 8 9 10 
$ b: Factor w/ 10 levels "A","B","C","D",..: 1 2 3 4 5 6 7 8 9 10 
3

請參閱?format。所述format函數返回:

類似的結構的「x」包含字符的第一個參數「X」的在 通用格式的元素的 表示的目的,並且在當前區域的編碼。

?cbindcbind回報

...矩陣相結合的「...」參數 逐列或行方式。 (例外:如果沒有輸入或 所有輸入被「NULL」,該值是「NULL」。)

和矩陣的所有元素都必須是相同的類,所以一切被強制爲字符。

+2

我知道你喜歡的data.frame解決方案,但如果你想用一個矩陣,你可以強迫你'month'到數字:'爲.nu​​meric(月)'和所有的數據將是數字。 – GSee

-1

F.Y.I.
當一列是「因子」時,直接/直接使用as.numeric將更改該列中的值。正確的方法是:

data.frame[,2] <- as.numeric(as.character(data.frame[,2])) 

找到更多的細節:Converting values to numeric, stack overflow

+0

這只是更多信息。約翰內斯已經很好地回答了這個問題。 –