【问题标题】:Using lubridate function to conditionally change year in date使用 lubridate 函数有条件地更改日期
【发布时间】:2021-05-28 05:45:07
【问题描述】:

所以我目前正在努力使用 if 函数更改日期的年份部分。

我的日期列看起来像这样(实际数据框中的值更多,因此不能手动解决):

Date
<S3: POSIXct>
2020-10-31
2020-12-31

我基本上想创建一个 if 命令(或任何其他方法),这样如果月份小于 12(即不是 12 月),那么年份就会增加 1。

到目前为止,我已经尝试使用 lubridate 包来做:

if (month(df$Date)<12) {
df$Date <- df$Date %m+% years(1)
}

但是,该函数似乎没有正确调节,而是每年添加一个,包括月份 = 12 的那些

任何帮助将不胜感激!

【问题讨论】:

  • if 要求它的条件是精确的长度 1(不是 0,不是 2 或更多),所以如果你的 df 不是 1 行,那应该提供一个明确的警告,你不应该这样做。有人可能会想试试ifelse,但那是ill-advised。可以尝试replace,它与ifelse 的命运不同。
  • 感谢您让我走上正轨,并开始研究我在下面发布的另一种方法

标签: r date datetime lubridate date-conversion


【解决方案1】:

你可以这样处理:

library(lubridate)

dates <- seq.Date(from = as.Date('2015-01-01'),
                  to = Sys.Date(),
                  by = 'months')
indicator <- month(dates) < 12

dates2 <- dates
dates2[indicator] <- dates[indicator] %m+% years(1)

res <- data.frame(dates, indicator, dates2)
> head(res, 25)
        dates indicator     dates2
1  2015-01-01      TRUE 2016-01-01
2  2015-02-01      TRUE 2016-02-01
3  2015-03-01      TRUE 2016-03-01
4  2015-04-01      TRUE 2016-04-01
5  2015-05-01      TRUE 2016-05-01
6  2015-06-01      TRUE 2016-06-01
7  2015-07-01      TRUE 2016-07-01
8  2015-08-01      TRUE 2016-08-01
9  2015-09-01      TRUE 2016-09-01
10 2015-10-01      TRUE 2016-10-01
11 2015-11-01      TRUE 2016-11-01
12 2015-12-01     FALSE 2015-12-01
13 2016-01-01      TRUE 2017-01-01
14 2016-02-01      TRUE 2017-02-01
15 2016-03-01      TRUE 2017-03-01
16 2016-04-01      TRUE 2017-04-01
17 2016-05-01      TRUE 2017-05-01
18 2016-06-01      TRUE 2017-06-01
19 2016-07-01      TRUE 2017-07-01
20 2016-08-01      TRUE 2017-08-01
21 2016-09-01      TRUE 2017-09-01
22 2016-10-01      TRUE 2017-10-01
23 2016-11-01      TRUE 2017-11-01
24 2016-12-01     FALSE 2016-12-01
25 2017-01-01      TRUE 2018-01-01

【讨论】:

  • 非常感谢您的解决方案!在那段时间我设法找到了我自己的,我已经在下面发布了!
【解决方案2】:

找到了一个不使用 if 命令的更直接的解决方案。

df$Date[month(df$Date)<12] <- df$Date[month(df$Date)<12] %m+% years(1)

这仍然使用lubridate包中的月份函数来获取条件

【讨论】:

  • 这几乎正是@tester 提出的,尽管没有使用中间indicator 变量。 (我建议你接受这个答案,尽管在这里保留这个答案很好。)
  • 为什么测试人员的回答更正确?指标变量没有增加任何好处
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 2021-07-10
  • 2021-06-16
相关资源
最近更新 更多