Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering my dataset by months using date column

I have a df (can be seen below) of data each month from 1998 to 2021. I with to divide my data into a new dfs of each season, so id have the winter months from Dec to Feb in one and so on. How would i extract all the data based on months 12, 01 and 02 from my data?

Data snipet;

sst_df
          date    sst  
1   1997-12-15 16.745 
2   1998-01-15 16.009 
3   1998-02-15 15.792 
4   1998-03-15 15.565 
5   1998-04-15 16.230 
6   1998-05-15 17.582 
7   1998-06-15 21.517 
8   1998-07-15 23.930 
9   1998-08-15 25.064 
10  1998-09-15 23.753 
11  1998-10-15 21.118 
12  1998-11-15 18.780 

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

library(dplyr)
library(lubridate)

dat <- tibble::tribble(
  ~date,    ~sst,  
  "1997-12-15", 16.745,
  "1998-01-15", 16.009, 
  "1998-02-15", 15.792, 
  "1998-03-15", 15.565, 
  "1998-04-15", 16.230, 
  "1998-05-15", 17.582, 
  "1998-06-15", 21.517, 
  "1998-07-15", 23.930,
  "1998-08-15", 25.064,
  "1998-09-15", 23.753,
  "1998-10-15", 21.118,
  "1998-11-15", 18.780
)

dat %>% 
  mutate(
    date = ymd(date)
  ) %>% 
filter(month(date) %in% c(12, 2, 1))

#> # A tibble: 3 × 2
#>   date         sst
#>   <date>     <dbl>
#> 1 1997-12-15  16.7
#> 2 1998-01-15  16.0
#> 3 1998-02-15  15.8

Created on 2022-07-07 by the reprex package (v2.0.1)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading