【问题标题】:Group data by year starting specific month [closed]从特定月份开始按年份分组数据[关闭]
【发布时间】:2019-07-11 08:54:59
【问题描述】:

我有称为 ddata 的大数据。它的日期字段范围从 2014 年到 2018 年。我想按 12 个月的时间段(从特定月份开始,例如 2014 年 4 月至 2015 年 3 月等)对每个县的案例进行分组。

我编写了仅在日历年执行结果的给定代码。但我想在任何 12 个月期间执行类似的结果,即从任何一个月开始(例如 2014 年 4 月至 2015 年 3 月、2015 年 4 月至 2016 年 3 月等......)

  ddata <- ddata %>%
               select(ID, Disease, DateReported, County) %>%
               mutate(calendar_year = year(Date)) %>%
               mutate(month = month(DateReported)) %>%
               filter(calendar_year >=2014) %>%
               group_by(County, calendar_year) %>%
               summarize(cases = n()) %>%
               spread(calendar_year, cases)

【问题讨论】:

标签: r dplyr


【解决方案1】:

您可以创建一个新列,例如假设您要从四月开始

start_month <- 4
ddata <- ddata %>%
               select(ID, Disease, DateReported, County) %>%
               mutate(custom_year = ifelse(month(Date)>= start_month, year, year-1))
               filter(custom_year >=2014) %>%
               group_by(County, custom_year) %>%
               summarize(cases = n()) %>%
               spread(custom_year, cases)

【讨论】:

    猜你喜欢
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-28
    • 2012-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多