gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 00:22:20 27 4
gpt4 key购买 nike

就我而言,我有一个数字向量(future_prices)。我使用来自另一个向量(这里:pred_commodity_prices$futuredays)的日期向量来创建月份的数字。之后,我使用 cbind 将月份绑定(bind)到数字向量。但是,发生的是数字向量变为非数字。你知道这是什么原因吗?当我使用 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

最佳答案

原因是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

关于R:数字向量在日期的 cbind 后变为非数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11151339/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com