Ravua1992
Ravua1992

Reputation: 23

Filter only if a condition is valid across time in r

I want to understand how can I use the filter function after grouping by ID. I want to filter ID where DV is less than 0.1 at all time >0. Time 0 is the baseline.

Below is the example for my initial data:

Input

Final expected output

Final output

Upvotes: 0

Views: 181

Answers (2)

Suhas Mehta
Suhas Mehta

Reputation: 19

THRESHOLD = 0.1
INITIAL_TIME = 0
filter(dat, ((DV < THRESHOLD) | (TIME == INITIAL_TIME)) & 
    (!ID %in% distinct(filter(dat,(DV > THRESHOLD) & 
    (TIME > INITIAL_TIME)) %>% select(ID))))

Upvotes: 0

r2evans
r2evans

Reputation: 160447

Fake data, since I don't have yours.

dat <- data.frame(
  ID   = c(1,1,1,          2,2,2,          3,3,3),
  TIME = c(0:2,            0:2,            0:2),
  DV   = c(100,0.01,0.01,  100,0.05,0.09,  100,0.01,5)
)

dat %>%
  group_by(ID) %>%
  filter(all(TIME < 1 | DV < 0.1)) %>%
  ungroup()
# # A tibble: 6 x 3
#      ID  TIME     DV
#   <dbl> <int>  <dbl>
# 1     1     0 100   
# 2     1     1   0.01
# 3     1     2   0.01
# 4     2     0 100   
# 5     2     1   0.05
# 6     2     2   0.09

Upvotes: 1

Related Questions