【问题标题】:Filter dates to show only the current month and 12 months ahead in R过滤日期以在 R 中仅显示当前月份和未来 12 个月
【发布时间】:2021-12-06 12:28:38
【问题描述】:

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

这是我的 df:

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

我试过这段代码,但返回一个空的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")

【问题讨论】:

  • Data.AnoData.Mes 的值是什么,它们来自哪里?请在您的示例中包含这些内容。

标签: r dplyr lubridate


【解决方案1】:

如果我正确理解您的问题,您希望 filter() 获取 DataDataReferencia 中年份和月份相同的日期,或者 DataReferencia 中的日期比 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 个月。

【讨论】:

  • 谢谢!我忘了包括这两列,对不起。
  • 不用担心,我很高兴这个解决方案有效
猜你喜欢
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 1970-01-01
  • 2018-10-08
  • 1970-01-01
  • 2023-01-25
  • 1970-01-01
  • 2021-07-29
相关资源
最近更新 更多