Home > Net >  Filter days after the local minimum of temperature
Filter days after the local minimum of temperature

Time:10-15

Here is the dummy example:

tribble(
  ~year,  ~day,  ~temp,
  2020,   90,    4,
  2020,   91,    3,
  2020,   92,    0,
  2020,   93,    2,
  2020,   94,    5,
  2021,   90,    2,
  2021,   91,    0,
  2021,   92,    2,
  2021,   93,    4,
  2021,   94,    6
)

In each year I want to cut out all the days before local minimum of temperature (here zero), so the result should be:

    year   day  temp
   <dbl> <dbl> <dbl>
 1  2020    93     2
 2  2020    94     5
 3  2021    92     2
 4  2021    93     4
 5  2021    94     6

How can I do it (preferably with dplyr)? Thanks in advance.

CodePudding user response:

Many ways, here's one with cumany:

tib %>% 
  group_by(year) %>% 
  filter(lag(cumany(temp == 0)))

#    year   day  temp
# 1  2020    93     2
# 2  2020    94     5
# 3  2021    92     2
# 4  2021    93     4
# 5  2021    94     6

An equivalent with cumsum:

tib %>% 
  group_by(year) %>% 
  filter(lag(cumsum(temp == 0) > 0))

or with row_number:

tib %>% 
  group_by(year) %>% 
  filter(row_number() > which(temp == 0))
  • Related