从日期对象中查找上周

Find last week from date object

我有一个日期对象,格式为 YYYY-MM-DD 多年。我想从中得到昨天、上周和上个月。 对于昨天,我可以简单地做 Sys.Data()-1 它给了我昨天,我可以将它与数据对象进行比较。

但是,我正在努力寻找上周和上个月。对于上个月,我可以使用 lubridate 包来获取 month(data)-1 上个月的数字。同样,我对一周的标准是应该从周一到周日。 lubridate 中的 week() 方法给出了一年中的周数。但由于我的数据是多年的,它们每年都会重复。

有没有办法从今天开始获取上个月和上周的日期,以便我可以将它们与我的日期对象进行比较。或者是否有其他更好的方法从该数据对象中查找上个月和上周?

例如,理想情况如下

        date       type
1 2021-04-09  yesterday
2 2021-04-01  last_week
3 2021-03-01 last_month

您可以借助 lubridate 函数。

library(dplyr)
library(lubridate)

df %>%
  mutate(yesterday = date - 1, 
         last_week = floor_date(date, 'week') - 6, 
         last_month = floor_date(date, 'month') %m-% months(1))

#        date  yesterday  last_week last_month
#1 2021-04-10 2021-04-09 2021-03-29 2021-03-01
#2 2019-02-03 2019-02-02 2019-01-28 2019-01-01
#3 2020-05-06 2020-05-05 2020-04-27 2020-04-01

数据

df <- data.frame(date = c(Sys.Date(), as.Date(c('2019-02-03', '2020-05-06'))))