【问题标题】:Error in as.Date.numeric() : 'origin' must be suppliedas.Date.numeric() 中的错误:必须提供“原点”
【发布时间】:2023-03-22 15:13:01
【问题描述】:

我收到了一篇论文,他们在其中包含了 R 文件作为他们的经验结果。不过,我在尝试运行他们的代码时遇到了一些问题:

data <- vni$R[198:length(vni$R)]; date <- vni$Date[198:length(vni$R)]
l <- length(data)
rw_length <- 52 # 52 weeks (~ 1 year)
bound <- vector()
avr <- vector()
for (i in (rw_length+1):l) {
  AVR.test <- AutoBoot.test(data[(i-rw_length):i],nboot=2000,"Normal",c(0.025, 0.975))
  bound <- append(bound, AVR.test$CI.stat)
  avr <- append(avr, AVR.test$test.stat)
}
lower <- bound[seq(1, length(bound), 2)]
upper <- bound[seq(2, length(bound), 2)]

results <- matrix(c(date[(rw_length+1):l],data[(rw_length+1):l],avr,upper, lower),ncol=5, dimnames = list(c(),c("Date", "Return", "AVR",  "Upper", "Lower")))

我收到以下错误:`

as.Date.numeric(e) 中的错误:必须提供“原点”`

对于results &lt;- matrix(c(date[(rw_length+1):l],data[(rw_length+1):l],avr,upper, lower),ncol=5, dimnames = list(c(),c("Date", "Return", "AVR", "Upper", "Lower")))

我的数据集是:

          Date       P             R
1   2001-03-23  259.60  0.0000000000
2   2001-03-30  269.30  0.0366840150
3   2001-04-06  284.69  0.0555748690
4   2001-04-13  300.36  0.0535808860
5   2001-04-20  317.76  0.0563146260
...
935 2019-02-15  950.89  0.0454163960
936 2019-02-22  988.91  0.0392049380
937 2019-03-01  979.63 -0.0094283770

你能帮我解决这个问题吗? 非常感谢!

【问题讨论】:

    标签: r date


    【解决方案1】:

    matrix 中的所有内容都必须是同一个类。当数字中有一个字符串时,通常会发现这种情况,其中

    m <- matrix(0, nr=2, nc=2)
    m
    #      [,1] [,2]
    # [1,]    0    0
    # [2,]    0    0
    m[1] <- "a"
    m
    #      [,1] [,2]
    # [1,] "a"  "0" 
    # [2,] "0"  "0" 
    

    在这种情况下,您有Date(第一列)和numeric(所有其他?不知道AutoBoot 是什么)。并且因为它试图从最复杂的强制转换为最复杂的(从numericDate),所以非Date 对象正在被转换。

    matrix(c(Sys.Date(), 1.1))
    # Error in as.Date.numeric(e) : 'origin' must be supplied
    

    因此,我建议尝试将其存储在 matrix 中是有根本缺陷的。如果你想在数字中存储一个Date 对象,你有两种选择:

    1. 将其存储为data.frame,其中每一列都可以有自己的类。
    2. "Date" 数据预转换为numeric 并将其存储为数字。这意味着如果/当您需要再次将日期归类为 Date 时,您将需要 as.Date(..., origin="1970-01-01")

    【讨论】:

    • 我觉得有趣的是as.Date(1.1) 本身可以正常工作而不会出错或抱怨...
    • 我已经将日期转换为数字,正如你所说的 date &lt;- as.numeric(date) 并且它有效!!!非常感谢!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    • 2011-02-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-01
    相关资源
    最近更新 更多