根据依赖条件过滤分组数据

问题描述 投票:0回答:1

我有一个日期(日期)和温度(度)的数据框。我试图按温度达到 5 或更低但后来达到 15 或更高的年份过滤此数据。时间跨度各不相同,但都是几年中几个月或几周的子集。 我正在使用 dplyr、purr 和 lubridate,但对其他软件包开放。

可重现的示例:

date<- as.Date(c("2020-01-01", "2020-01-02", "2020-01-03", "2020-01-04",
"2021-01-01", "2021-01-02", "2021-01-03", "2021-01-04",
"2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04",
"2023-01-01", "2023-01-02", "2023-01-03", "2023-01-04"))

degrees<- c(10,5,10,15,20,6,10,15,0,0,10,20,10,8,20,15)

df<-data.frame(date,degrees)

我期望的输出如下。

日期
2020-01-01 10
2020-01-02 5
2020-01-03 10
2020-01-04 15
2022-01-01 0
2022-01-02 0
2022-01-03 10
2022-01-04 20
r dplyr purrr lubridate
1个回答
0
投票
library(tidyverse)

df |> 
  mutate(year = year(date)) |>
  mutate(m = any(cumsum(degrees<= 5) > 0 & degrees >= 15), .by = year) |> 
  filter(m) |>
  select(date, degrees)
© www.soinside.com 2019 - 2024. All rights reserved.