代码之家  ›  专栏  ›  技术社区  ›  Joe

使用日期列按月份筛选数据集

r
  •  0
  • Joe  · 技术社区  · 3 年前

    我有1998年至2021年每个月的数据df(如下所示)。我需要将我的数据划分为每个季节的一个新的dfs,所以我将12月到2月的冬季月份放在一个月内,以此类推。我如何从我的数据中提取基于12月、01月和02月的所有数据?

    数据狙击手;

    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 
    
    2 回复  |  直到 3 年前
        1
  •  1
  •   Shafee ikashnitsky    3 年前
    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
    
    

    创建于2022-07-07由reprex包(v2.0.1)

        2
  •  1
  •   Mohamed Desouky    3 年前

    用它来提取冬季月份

    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)
    
    
    • 输出
      month    sst
    1    12 16.745
    2     1 16.009
    3     2 15.792