【问题标题】:Error in charToDate(x)charToDate(x) 中的错误
【发布时间】:2013-04-30 10:30:22
【问题描述】:

我想选择仅包含当前日期信息的 data.frame 子集。

today = Sys.Date()
LasttDate = paste("'",today,"'",sep = "")
> LastDate
[1] "'2013-04-30'"

选择是通过以下包含日期的代码执行的,并且有效

Lastdbdata = dbdata[dbdata$DateNav == '2013-04-30',]

如果我们不想一直写日期,但我们希望在运行代码时自动选择它,但我们可以改为写

    Lastdbdata = dbdata[dbdata$DateNav == LastDate,]
    Errore in charToDate(x) : 
    character string is not in a standard unambiguous format

但它不起作用并返回上述错误。 解决这个错误的诀窍是什么?

【问题讨论】:

    标签: r date dataframe


    【解决方案1】:

    您收到该错误是因为DateNav 已经是Date 格式,而Lastdate 不是。比较 DateNavtoday 应该可以解决问题:

    > Sys.Date()
    [1] "2013-04-30"
    > Sys.Date()==as.Date("2013-04-30")
    [1] TRUE
    > Sys.Date()==as.Date("'2013-04-30'")
    Error in charToDate(x) : 
      character string is not in a standard unambiguous format
    

    事实上,即使DateNav 不是Date 格式,您也可以/应该直接与today 比较。

    > Sys.Date()=="2013-04-30"
    [1] TRUE
    

    我不确定插入单引号的基本原理是什么。如果您出于其他原因想将日期转换为字符,则总有

    > as(Sys.Date(),"character")
    [1] "2013-04-30"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-02
      • 2020-03-29
      • 2015-01-27
      • 2019-09-04
      • 2021-12-30
      • 2020-03-03
      • 2019-08-27
      • 1970-01-01
      相关资源
      最近更新 更多