[英]Using lubridate function to conditionally change year in date
因此,我目前正在努力使用 if function 更改日期的年份部分。
我的日期列看起來像這樣(在真正的 dataframe 中有更多的值,所以它不能是手動解決方案):
Date
<S3: POSIXct>
2020-10-31
2020-12-31
我本質上想創建一個 if 命令(或任何其他方法),這樣如果月份小於 12(即不是 12 月),那么年份就會增加 1。
到目前為止,我已經嘗試使用 lubridate package 來做:
if (month(df$Date)<12) {
df$Date <- df$Date %m+% years(1)
}
然而,function 似乎沒有正確調節,而是每年增加一個,包括月份=12
任何幫助將不勝感激!
你可以這樣處理它:
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
找到了一個不使用 if 命令的更直接的解決方案。
df$Date[month(df$Date)<12] <- df$Date[month(df$Date)<12] %m+% years(1)
這仍然使用lubridate package中的月份function來獲取條件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.