dplyr mutate with str_locate_all

I would like to add the Start and End positions of Strings into a df. I know how to do it with str_locate but how do I bind all expected hits using str_locate_all?

Example for str_locate:

library(dplyr)
library(stringr)

pattern <- "HelloHiHelloHi"

df <- data.frame(
  Text = c("Hello", "HelloHi", "Hi")
)

df <- df %>% rowwise() %>% mutate(Start = str_locate(pattern, Text)[[1]],
                    End = str_locate(pattern, Text)[[2]]) 

#result

  Text    Start   End
  <chr>   <int> <int>
1 Hello       1     5
2 HelloHi     1     7
3 Hi          6     7
library(tidyverse)
pattern <- "HelloHiHelloHi"

dfin <- data.frame(
  Text = c("Hello", "HelloHi", "Hi")
)


df <- dfin %>%
  rowwise() %>%
  mutate(sla = list(
    as.data.frame(
      str_locate_all(pattern,Text)
    )
  )) %>%
  unnest(c(sla))
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.