【问题标题】:Turning an actual date into an integer value in R将实际日期转换为 R 中的整数值
【发布时间】:2015-10-08 11:20:01
【问题描述】:

使用 R,我希望能够将格式为“2014-12-31”的日期转换为整数 20141231,以创建序列号。

我的目标只是能够完成这个用户问题的 REVERSE (Turning an integer string date into an actual date)。

感谢提供的任何帮助。

【问题讨论】:

    标签: r date integer


    【解决方案1】:

    以这种方式简单地格式化日期,然后在结果上调用as.integer

    R> as.integer(format(Sys.Date(), "%Y%m%d"))
    [1] 20151008
    

    如果您的日期不是日期,而是字符串:要么先将其转换为日期,要么在调用as.integer 之前删除"-"

    R> dateString <- "2014-12-31"
    R> as.integer(format(as.Date(dateString), "%Y%m%d"))
    [1] 20141231
    R> as.integer(gsub("-", "", dateString))
    [1] 20141231
    

    【讨论】:

    • 感谢您的快速回复@joshua-ulrich。在尝试使用此解决方案时,我收到以下错误:&gt; as.integer(format(testdate, "%Y%m%d")) Error in format.default(testdate, "%Y%m%d") : invalid 'trim' argument
    • @Qaribbean 您的“日期”不是Date 变量。使用as.Date 或其他答案中的建议。
    • @Qaribbean:你说你有一个日期,所以我假设它是一个 Date 对象。显然,它只是一个字符串。
    • @joshua-ulrich 很抱歉没有澄清。
    • @joshua-ulrich 感谢您更新的答案,这也很有帮助!
    【解决方案2】:

    或者如果你已经有了角色日期:

    a <- "2015-03-15"
    as.integer(gsub(pattern = "-", replacement="", x = a))
    #[1] 20150315
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-02
      • 1970-01-01
      • 2021-09-10
      • 2019-04-22
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多