Need help organizing dates

I need help classifying some date variables. I currently have a data set for that has an entry for every day for a twenty-year period, and I want to get averages for each month. For example, the data looks like this:

Screen Shot 2021-12-02 at 6.19.29 PM

And I want to get the average ranger_peds value for each month, how would I go about coding for that? In the end I only want to have one entry for each month, so instead of having 2008-01-01, 2008-01-02, etc... it would look like 2008-01 and then another entry for 2008-02, etc...

Thank you!

1 Like

See the FAQ: How to do a minimal reproducible example reprex for beginners. Some representative data (doesn't have to be all the data or even real data) attracts more answers.

I think that it is an example for you.

dates <- c("2004-02-06","2005-05-06","2006-06-06")
dates_New<-format(as.Date(dates), "%Y-%m")
dates_New

I created a date called year_month which is based on the year and month, so all days in February 2014 will be 2014-02-01. Group by year_month and then calculate the mean for each group.

library(tidyverse)
library(lubridate)


dates <- c("2004-02-06","2004-02-08","2006-02-06", "2006-02-28")
values <- c(28, 32, 20, 24)

data.frame(dates, values) %>%
  mutate(year_month = make_date(year = year(dates), month = month(dates))) %>%
  group_by(year_month) %>%
  summarise(mean = mean(values)) 
#> # A tibble: 2 × 2
#>   year_month  mean
#>   <date>     <dbl>
#> 1 2004-02-01    30
#> 2 2006-02-01    22

Created on 2021-12-04 by the reprex package (v2.0.1)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.