过滤日期以仅在 R 中显示当前月份和未来 12 个月

Filter dates to show only the current month and 12 months ahead in R

我有一个带有一些日期的 df,我想过滤日期以仅显示当前月份和未来 12 个月。

这是我的 df:

我想为 Date 列中的每个日期保留 DataReferencia 列中的当前月份和未来 12 个月的日期,然后从 Value栏目。对于上述日期,在 2003-01-17 日,它将是 DataReferencia 列中的日期 2003-01-01 和 2003-12-01。此 df 从 2003-01 运行到 2020-12。

我试过这段代码,但是 returns 一个空的 df:

library(dplyr)
library(lubridate)

test %>%
  filter(year(DataReferencia) == Data.Ano & month(DataReferencia) == Data.Mes + 11,
         month(DataReferencia) == Data.Mes)

我的dput:

structure(list(Instituicao = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1), Data = structure(c(12069, 12069, 12069, 
12069, 12069, 12069, 12069, 12069, 12069, 12069, 12069, 12069, 
12070, 12070, 12070, 12070, 12070), class = "Date"), DataReferencia = structure(c(12053, 
12084, 12112, 12143, 12173, 12204, 12234, 12265, 12296, 12326, 
12357, 12387, 12053, 12084, 12112, 12143, 12173), class = "Date"), 
    Valor = c(26, 24, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 
    26, 24, 22, 22, 22), DataReuniao = structure(c(12073, 12073, 
    12073, 12073, 12073, 12073, 12073, 12073, 12073, 12073, 12073, 
    12073, 12073, 12073, 12073, 12073, 12073), class = "Date"), 
    Reuniao = c(80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 80, 
    80, 80, 80, 80, 80), MetaSelic = c(25.5, 25.5, 25.5, 25.5, 
    25.5, 25.5, 25.5, 25.5, 25.5, 25.5, 25.5, 25.5, 25.5, 25.5, 
    25.5, 25.5, 25.5)), row.names = c(NA, 17L), class = "data.frame")

如果我对你的问题的理解正确,你想 filter() DataDataReferencia 中年份和月份相同的日期,或者 [=13] 中的日期=]比Data提前11个月。我不确定您的失败代码中的 Data.AnoData.Mes 是什么,或者这些是否是列名称的翻译名称?

这段代码可以完成工作:

test %>%
    filter(
        format(DataReferencia, format = '%Y-%m') == format(Data, format = '%Y-%m')
        | format(DataReferencia, format = '%Y-%m') == format(Data + months(11), format = '%Y-%m')
    )


#   Instituicao       Data DataReferencia Valor DataReuniao Reuniao MetaSelic
# 1           1 2003-01-17     2003-01-01    26  2003-01-21      80      25.5
# 2           1 2003-01-17     2003-12-01    22  2003-01-21      80      25.5
# 3           1 2003-01-18     2003-01-01    26  2003-01-21      80      25.5

我们使用format()以年月格式检索数据列的日期;我们使用 format = %Y-%m、使用符号和缩写解释 here 来指定它;基本上 %Y 表示(4 位数)年份,%m 是(2 位数)月份。因为这仍然是 R 识别的日期格式,它允许在 filter().

中的第二个条件中添加 11 个月