Is there an equivalent to dplyr::between for character vectors?

Viewed 136

I am using a tibble, and I want to extract rows between two regular expressions.

First, I make a new column where I detect the regular expressions, and mark them.

tib <- tibble::tibble(
    x = c('a', 'b', 'c', 'd', 'e'),
    y = c(F, T, F, T, F)
)

# A tibble: 5 x 2
  x     y    
  <chr> <lgl>
1 a     FALSE
2 b     TRUE 
3 c     FALSE
4 d     TRUE 
5 e     FALSE

Expected result:

tib %>% 
    dplyr::filter(
        dplyr::between(x, T, T)
    )

# A tibble: 2 x 2
  x     y    
  <chr> <lgl>
1 b     TRUE 
2 c     FALSE
3 d     TRUE 

dplyr::between() is used for number vectors, however. Anyway, it doesn't return the rows between two TRUE objects.

Is there an equivalent to dplyr::between() for character vectors? Or maybe there is another way someone might suggest that uses the boolean objects I have created.

Regards,

3 Answers

First thing that comes to my mind would be slice in combination with which˙, for example:

library(dplyr)

tib %>%
  slice(first(which(x == 'b')):last(which(x == 'd')))

Or with y itself:

tib %>%
  slice(first(which(y)):last(which(y)))

Output:

# A tibble: 3 x 2
  x     y    
  <chr> <lgl>
1 b     TRUE 
2 c     FALSE
3 d     TRUE 

One way to do it is to get the indices of TRUE and create the sequence, i.e.

v1 <- which(tib$y)
tib[v1[1]:tail(v1, 1),]

# A tibble: 3 x 2
  x     y    
  <chr> <lgl>
1 b     TRUE 
2 c     FALSE
3 d     TRUE 

I'm not sure if you understand that function right. But you could use regexpr.

r <- regexpr("TFT", paste(substr(as.character(tib$y), 1, 1), collapse=""))
tib[r:(r + attr(r, "match.length") - 1), ]
#   x     y
# 2 b  TRUE
# 3 c FALSE
# 4 d  TRUE
Related