Search code examples
rlapplysapply

Extract 'end' locations from multiple locations in str_locate_all in R?


If we locate a substring among a vector of strings like so

library(stringr)
library(dplyr)

x <- c("ldksfABCskdlfj",
       "kABCz",
       "skdlfjlsjfABCksdfpjfkj")

x %>% str_locate_all("ABC")

we get

[[1]]
     start end
[1,]     6   8

[[2]]
     start end
[1,]     2   4

[[3]]
     start end
[1,]    11  13

How can I extract just the end locations? (i.e. 8, 4, 13)

What I've tried so far

x %>% str_locate_all("ABC") %>% sapply(function(x) { .[1,2] })
# Error in .[1, 2] : incorrect number of dimensions

Solution

  • Almost there. Here's a way to do:

    x %>% str_locate_all("ABC") %>% sapply(., function(x) x[,2])