使用 lubridate 在 R 中修改 POSIXct 格式的日期

Modify dates in POSIXct format in R using lubridate

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

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 年的日期上加上一年,使输出也是一个日期?

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"

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

但是既然你一直在使用 lubridate 包,为什么不使用它的 year<- 替换功能来用不同的年份替换年份呢?有了它我们就可以一起避免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() 调用之前获取 class,然后将其分配回去。

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

例子见help(ifelse)。但我认为 year<- 会在这里帮助你更多,因为你已经在使用 lubridate 包。