【问题标题】:Modify dates in POSIXct format in R using lubridate使用 lubridate 在 R 中修改 POSIXct 格式的日期
【发布时间】:2016-02-03 20:18:29
【问题描述】:

我有五个日期,格式如下:

five_dates <- c("2015-04-13 22:56:01 UTC", "2015-04-13 23:00:29 UTC", "2014-04-13 23:01:22 UTC", "2013-04-13 23:01:39 UTC", "2013-04-13 23:01:43 UTC")

使用lubridate 包,我通过执行以下操作来处理它们:

five_dates <- lubridate::ymd_hms(five_dates)
str(five_dates)
[1] POSIXct[1:5], format: "2015-04-13 22:56:01" "2015-04-13 23:00:29" "2014-04-13 23:01:22" "2013-04-13 23:01:39" "2013-04-13 23:01:43"

我想在 2013 年的日期上加一年:

five_dates <- ifelse(lubridate::year(five_dates) < 2014, five_dates + years(1), five_dates)

但是这样做会导致这个输出:

five_dates
[1] 1428965761 1428966029 1397430082 1397430099 1397430103

如何在 2013 年的日期上加上一年,这样输出也是一个日期?

【问题讨论】:

    标签: r date lubridate


    【解决方案1】:

    ifelse 删除日期格式。您需要将其转换回来:

    five_dates <- as.POSIXct(five_dates, origin="1970-01-01", tz = "UTC")
    

    给出:

    > five_dates
    [1] "2015-04-13 22:56:01 UTC" "2015-04-13 23:00:29 UTC"
    [3] "2014-04-13 23:01:22 UTC" "2014-04-13 23:01:39 UTC"
    [5] "2014-04-13 23:01:43 UTC"
    

    实现相同效果的ifelse 操作的替代方案:

    five_dates <- five_dates + years(as.integer(year(five_dates) < 2014))
    

    给予:

    > five_dates
    [1] "2015-04-13 22:56:01 UTC" "2015-04-13 23:00:29 UTC"
    [3] "2014-04-13 23:01:22 UTC" "2014-04-13 23:01:39 UTC"
    [5] "2014-04-13 23:01:43 UTC"
    

    【讨论】:

      【解决方案2】:

      问题是ifelse()。它剥离了属性。

      但既然您仍然使用 lubridate 包,为什么不使用它的year&lt;- 替换功能将年份替换为不同的年份呢?有了它,我们可以一起避免ifelse()

      yr <- 2013
      year(five_dates[year(five_dates) == yr]) <- yr + 1
      five_dates
      # [1] "2015-04-13 22:56:01 UTC" "2015-04-13 23:00:29 UTC"
      # [3] "2014-04-13 23:01:22 UTC" "2014-04-13 23:01:39 UTC"
      # [5] "2014-04-13 23:01:43 UTC"
      

      或者使用您的代码,您可以在 ifelse() 调用之前获取类,然后将其分配回去。

      cl <- class(five_dates)
      five_dates <- ifelse(...)
      class(five_dates) <- cl
      

      示例在help(ifelse) 中显示。但我认为year&lt;- 会在这里为您提供更多帮助,因为您已经在使用 lubridate 包。

      【讨论】:

      • 我选择这个答案是因为我想我更喜欢留在lubridate 土地。
      • 好答案。 @JoshuaRosenberg 我的回答中的第二个选项也在 lubridate-land ;-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      相关资源
      最近更新 更多