R:数字向量在日期cbind之后变为非数字

Fab*_*olz 12 binding r date numeric

在我的例子中,我有一个数字向量(future_prices).我使用另一个向量的日期向量(这里:pred_commodity_prices $ futuredays)来创建月份的数字.之后我使用cbind将月份绑定到数字向量.然而,发生的是数字向量变为非数字.你知道这是什么原因吗?当我使用as.numeric(future_prices)时,我得到了奇怪的值.什么可以替代?谢谢

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 
Run Code Online (Sandbox Code Playgroud)

joh*_*nes 23

原因是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
Run Code Online (Sandbox Code Playgroud)