-2

I have big data called ddata. It has date field ranging from 2014 to 2018. I want to group the cases from each county by 12-month period(starting from specific month eg. April 2014- March 2015, and so on..).

I wrote given code that executes the result only for the calendar year. but I want to execute similar result for any 12-month period i.e. starting at any month (e.g. April 2014 to March 2015, April 2015 to March 2016 and so on..)

  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)
datagig
  • 1
  • 1
  • 1
    Welcome to StackOverflow. Have a look here and here https://stackoverflow.com/questions/50702804/extract-fiscal-year-with-r-lubridate https://stackoverflow.com/questions/33877714/assigning-dates-to-fiscal-year – TimTeaFan Jul 11 '19 at 09:11
  • 1
    Possible duplicate of [Extract Fiscal Year with R Lubridate](https://stackoverflow.com/questions/50702804/extract-fiscal-year-with-r-lubridate) – TimTeaFan Jul 11 '19 at 09:11

1 Answers1

1

You can create a new column, for example let's assume that you want to start in April

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)
fmarm
  • 4,209
  • 1
  • 17
  • 29