Lyndz
Lyndz

Reputation: 423

Using dplyr filter with multiple conditions

I have the following data set.

There are three columns: Pentad, A, and B.

library(zoo)
library(rlang)
library(tidyverse) 

dat<-structure(list(Pentad = 50:73, A = c(152.796, 
109.678, 91.5594,115.155, 135.9, 202.441, 71.6951, 
88.3894, 261.962,135.853, 89.3425, 110.674, 100.558, 
173.507, 87.2157, 86.6425, 75.1852, 57.403, 62.5705, 
49.6846, 52.0257, 92.819, 105.419, 97.7598), 
B = c(145.402, 110.109, 83.1076, 95.3952, 148.571, 
119.178, 56.5031, 76.2635, 260.443, 109.705, 62.3749, 
100.322, 88.4134, 135.721, 63.1486, 69.7161, 62.3886, 
46.4513, 52.4546, 42.7725, 45.7643, 79.5419, 79.9434, 
87.6405)), class = "data.frame", row.names = c(NA, 
-24L))

I would like to implement the following condition in R.

[1] V1 should be between 0 and 90 at the time step (excluding 0 and 90)

[2] In the succeeding FOUR time steps (including the 
timestep in [1]), V1 between 0 and 90 in AT LEAST THREE timesteps

What I have so far:

 test2 <- function(dat, column_name){ 
   dat %>%
   rownames_to_column() %>%
   filter((.data[[column_name]] > 0 & .data[[column_name]] < 90) & 
         rollsum(.data[[column_name]] > 0 & .data[[column_name]] < 90, 4, fill = NA, align = 
                   "left") >= 3) %>%
   slice(1) -> result
  return(result)
}

out <- colnames(dat2) %>% 
  set_names %>% 
  map_dfr(~ test2(dat2, .x), .id = 'Col_ID')

PROBLEM:

I want to get the timestep/pentad value where the above three conditions are true for both the 2nd (column A) and 3rd columns (column B).

That is, the timestep when both columns satisfy the conditions at the same time.

The expected output is Pentad 64.

Any idea how can I implement this in R?

I'll appreciate any help.

Upvotes: 0

Views: 115

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388797

Here's an attempt very close to OP's attempt.

library(dplyr)
library(zoo)

test2 <- function(dat) {
   dat %>%
      filter_at(vars(A:B), all_vars(. > 0 & . < 90 & 
                     rollsum(. > 0 & . < 90, 4, fill = NA) >= 3)) %>%
       slice(1L)
}

test2(dat)

#  Pentad       A       B
#1     64 87.2157 63.1486

Upvotes: 1

Related Questions