【问题标题】:How to define the column type of a data frame as date? [duplicate]如何将数据框的列类型定义为日期? [复制]
【发布时间】:2020-01-15 12:42:18
【问题描述】:

我想用几列初始化一个数据框(没有任何原始条目),其中一列是日期类型。数据框已初始化,稍后将通过 rbind 插入新条目。

不幸的是,我找不到将 Date 指定为类型的方法,更不用说如何声明其格式了。

df <- data.frame(Date=Date(format="%Y-%m-%d"),Value1=integer(),Value2=integer())

但我无法超越这个错误

Error in Date(format = "%Y-%m-%d") : could not find function "Date"

知道如何解决这个问题吗?

【问题讨论】:

    标签: r date dataframe rstudio


    【解决方案1】:

    尝试使用as.Date(character()),例如

    df <- data.frame(Date=as.Date(character()),
                     Value1=integer(),
                     Value2=integer())
    class(df$Date)
    
    [1] "Date"
    

    【讨论】:

      【解决方案2】:

      lubridate 与模板一起使用:

      df <- data.frame(Date=lubridate::ymd(),Value1=integer(),Value2=integer())
      sapply(df, class)
      

      【讨论】:

        猜你喜欢
        • 2020-05-05
        • 1970-01-01
        • 2023-02-08
        • 2022-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-02
        • 2017-07-15
        相关资源
        最近更新 更多