繁体   English   中英

在 R 中使用 tidyverse lubridate 在日期之间过滤

[英]Filter between dates using tidyverse lubridate in R

我有一个地下水位和相关日期的数据集。 我想做一些非常简单的事情:用与日期相关的季节对列进行变异。

示例数据集:

Watertable date
2          2018-05-03
5          2018-08-01
12         2019-01-03
3          2019-07-29
4          2020-11-09
5          2021-08-22

预期输出:

Watertable date          season
2          2018-05-03    Spring
5          2018-08-01    Summer
12         2019-01-03    Winter
3          2019-07-29    Summer
4          2020-10-09    Fall
5          2021-08-22    Summer

使用lubridate包将日期转换为“日期”。 我可以通过仅case_when月份和日期的额外列并在该列上使用case_when来创建季节列,但这似乎是一个额外的不必要步骤。

我的问题:我如何使用mutatecase_when创建新的“季节”列,而不必创建只有月份和日期的新列。 即我想使用 lubridate 来选择省略年份的日期段,因为新列仅依赖于日期中的月和日值。

我希望这个问题很清楚。 很高兴在被要求时提供其他信息。

starting dates seasons:
spring = 20 march
summer = 20 june
fall = 22 september
winter = 21 december

一种方法是使所有观察中的“年份”通用,然后使用case_when

library(dplyr)
library(lubridate)
df %>% 
    mutate(date1 =  as.Date(format(date, '2021-%m-%d')), 
        season = case_when(between(date1, ymd('2021-03-20'), ymd('2021-06-19'))
             ~ 'Spring',
      between(date1, ymd('2021-06-20'), ymd('2021-09-22'))
         ~ 'Summer', 
     between(date1, ymd('2021-09-22'), ymd('2021-12-21')) ~ 'Fall', 
       TRUE ~ 'Winter'), date1 = NULL)

-输出

 Watertable       date season
1          2 2018-05-03 Spring
2          5 2018-08-01 Summer
3         12 2019-01-03 Winter
4          3 2019-07-29 Summer
5          4 2020-11-09   Fall
6          5 2021-08-22 Summer

数据

df <- structure(list(Watertable = c(2L, 5L, 12L, 3L, 4L, 5L), date = structure(c(17654, 
17744, 17899, 18106, 18575, 18861), class = "Date")), row.names = c(NA, 
-6L), class = "data.frame")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM