【问题标题】:Calculation using the date function使用日期函数计算
【发布时间】:2017-12-27 10:00:06
【问题描述】:

需要获得每年最后一个月的销售额。

   Month    Sales
01-03-2018  2351
01-06-2018  4522
01-09-2018  3632
01-12-2018  6894
01-03-2019  5469
01-06-2019  6546
01-09-2019  7885
01-12-2019  6597
01-03-2020  7845
01-06-2020  6894
01-09-2020  5469
01-12-2020  6546
01-03-2021  2351
01-06-2021  4522
01-09-2021  3632
01-12-2021  6546
01-03-2022  7885
01-06-2022  6597
01-09-2022  7845
01-12-2022  6894

在这里,我想查找一年中每 12 个月的销售额。 输出应该如下:

Month   Sales
01-12-2018  6894
01-12-2019  6597
01-12-2020  6546
01-12-2021  6546
01-12-2022  6894

我可以选择表格中的每一行,但我想使用日期函数来完成。请帮忙。

【问题讨论】:

    标签: r date lubridate


    【解决方案1】:

    确保您的列 Month 设置为日期变量并使用 format 获取月份,即

    #Make sure it is a date variable
    df$Month <- as.POSIXct(df$Month, format = '%d-%m-%Y')
    
    df[format(df$Month, '%m') == 12,]
    

    给出,

           Month Sales
    4  2018-12-01  6894
    8  2019-12-01  6597
    12 2020-12-01  6546
    16 2021-12-01  6546
    20 2022-12-01  6894
    

    【讨论】:

      【解决方案2】:

      startsWith 的一种方式:

      #Month needs to be of character type
      df[startsWith(df$Month, '01-12-'), ]
      #        Month Sales
      #4  01-12-2018  6894
      #8  01-12-2019  6597
      #12 01-12-2020  6546
      #16 01-12-2021  6546
      #20 01-12-2022  6894
      

      【讨论】:

      • 也许值得一提的是,该变量需要是一个字符才能工作
      猜你喜欢
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多