Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:数字向量在cbind日期后变为非数字_R_Date_Binding_Numeric - Fatal编程技术网

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

R:数字向量在cbind日期后变为非数字,r,date,binding,numeric,R,Date,Binding,Numeric,我有一个数字向量(未来价格)。我使用另一个向量的日期向量(这里:pred_commodity_prices$futuredays)来创建月份的数字。之后,我使用cbind将月份绑定到数值向量。然而,发生的情况是数值向量变成了非数值向量。你知道这是怎么回事吗?当我使用as.numeric(未来价格)时,我会得到奇怪的值。还有什么替代方案?谢谢 head(future_prices) pred_peak_month_3a pred_peak_quarter_3a 1 68.33

我有一个数字向量(未来价格)。我使用另一个向量的日期向量(这里:pred_commodity_prices$futuredays)来创建月份的数字。之后,我使用cbind将月份绑定到数值向量。然而,发生的情况是数值向量变成了非数值向量。你知道这是怎么回事吗?当我使用as.numeric(未来价格)时,我会得到奇怪的值。还有什么替代方案?谢谢

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 
head(未来价格)
前高峰月前高峰季度
1           68.33907             62.37888
2           68.08553             62.32658
是数字(未来价格)
[1] 真的
>月=格式(如.POSIXlt.date(商品前价格$futureday),“%m”)
>未来价格主管(未来价格)
前高峰月前高峰季度月
1 "68.3390747063745"   "62.3788824938719"     "01"
是数字(未来价格)
[1] 假的

请参见
格式
format
函数返回:

结构类似于包含字符的“x”的对象 a中第一个参数“x”的元素表示形式 通用格式,并使用当前区域设置的编码

?cbind
cbind
返回

。。。组合“…”参数的矩阵 按列或按行。(例外情况:如果没有输入或 所有输入均为“NULL”,值为“NULL”。)


而且矩阵的所有元素必须属于同一类,因此所有元素都强制为字符。

原因是
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
nF.Y.I.
当一列为“因子”时,简单/直接使用
as.numeric
将更改该列中的值。正确的方法是:

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

data.frame[,2]我知道您喜欢data.frame解决方案,但是如果您想使用矩阵,您可以将
month
强制为numeric:
as.numeric(month)
并且您的所有数据都是数字的。这只是为了了解更多信息。约翰尼斯已经很好地回答了这个问题。