1
votes

consider the following tibble:

library(tidyverse)
a <- tibble(id = 1:5, val = c(-1,-2,0,1,-1))

I would like to select only certain rows in a: namely I want to delete lines from the top of a until the first remaining row has a non-negative value in val. So in my example above I would like to delete the first two rows (since val is negative there) and then keep all subsequent rows.

I managed to find a workaround solution:

idx <- which(a$val >= 0) %>% min()
a %>% slice(idx:nrow(a))
# A tibble: 3 x 2
     id   val
  <int> <dbl>
1     3  0   
2     4  1.00
3     5 -1.00

I feel like there is a more elegant solution within the tidyverse. Any hints? Thank you.

1

1 Answers

1
votes

We can use cumsum on the logical vector (val >=0)) and slice elements that are not 0

a %>% 
  slice(which(cumsum(val >=0)!=0))

Or with filter

a %>%
  filter(cumsum(val>=0) > 0)
# A tibble: 3 x 2
#     id   val
#   <int> <dbl>
#1     3  0   
#2     4  1.00
#3     5 -1.00