【问题标题】:Grouping and Summing Data by Irregular Time Intervals (R language)按不规则时间间隔对数据进行分组和求和(R 语言)
【发布时间】:2020-12-19 06:29:15
【问题描述】:

我在这里查看 stackoverflow 帖子:R: Count Number of Observations within a group

在这里,按每月(以及每周)间隔创建和汇总/分组每日数据:

library(xts)
library(dplyr)

#create data

date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")

date_decision_made <- format(as.Date(date_decision_made), "%Y/%m/%d")

property_damages_in_dollars <- rnorm(731,100,10)

final_data <- data.frame(date_decision_made, property_damages_in_dollars)


# weekly

weekly = final_data %>%
    mutate(date_decision_made = as.Date(date_decision_made)) %>%
    group_by(week = format(date_decision_made, "%W-%y")) %>%
    summarise( total = sum(property_damages_in_dollars, na.rm = TRUE), Count = n())


# monthly 

final_data %>%
    mutate(date_decision_made = as.Date(date_decision_made)) %>%
    group_by(week = format(date_decision_made, "%Y-%m")) %>%
    summarise( total = sum(property_damages_in_dollars, na.rm = TRUE), Count = n())

似乎 R (https://www.rdocumentation.org/packages/base/versions/3.6.2/topics/format) 中的“格式”语句被用于指示计算机以某个固定间隔“分组和求和”数据。

我的问题:有没有办法“指示”计算机以不规则的时间间隔“分组和求和”?例如。按 11 天周期,按 3 个月周期,按 2 年周期? (我猜3个月可以写成90天……2年可以写成730天)。

这可能吗?

谢谢

【问题讨论】:

    标签: r dplyr group-by sum aggregate


    【解决方案1】:

    您可以使用 lubridate 的ceiling_date/floor_date 不定期地创建群组。

    library(dplyr)
    library(lubridate)
    
    final_data %>%
      mutate(date_decision_made = as.Date(date_decision_made)) %>%
      group_by(group = ceiling_date(date_decision_made, '11 days')) %>%
      summarise(amount = sum(property_damages_in_dollars))
    

    您还可以指定间隔,例如 ceiling_date(date_decision_made, '3 years')ceiling_date(date_decision_made, '2 months')

    【讨论】:

      【解决方案2】:

      使用data.table

      library(data.table)
      library(lubridate)
      setDT(final_data)[,  .(amount = sum(property_damages_in_dollars)),
            ,.(group = ceiling_date(as.IDate(date_decison_made), "11 days"))]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-07
        • 2021-07-20
        • 1970-01-01
        • 2012-07-07
        • 1970-01-01
        • 2018-09-23
        • 2023-03-16
        • 1970-01-01
        相关资源
        最近更新 更多