Home > Software engineering >  Filtering my dataset by months using date column
Filtering my dataset by months using date column

Time:07-07

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 

CodePudding user response:

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)

CodePudding user response:

Use this to extract the winter months

library(lubridate)
library(dplyr)

sst_df |> mutate(month = month(date)) |>
 mutate(season = case_when(month %in% c(12,1,2) ~ "winter", between(month , 3 , 5) ~ "spring" ,
between(month , 6 , 8) ~ "summer" ,
between(month , 9 , 11) ~ "autumn")) |>
filter(season == "winter") |> select(month , sst)

  • output
  month    sst
1    12 16.745
2     1 16.009
3     2 15.792
  •  Tags:  
  • r
  • Related