linuxiaobai
linuxiaobai

Reputation: 67

stringr::str_locate return first occurence of the given pattern

While I want to find the location of a sub-string in a string, I have the following code and result. I think the returned value should be 3 and 1, but I got 3 for both records. How can I get the correct result? I am using R 3.5.3 with stringr 1.4.0.

t1 <- tibble(x = c("aaded", "dedere"))
t1
# A tibble: 2 x 1
  x     
  <chr> 
1 aaded 
2 dedere

bb <- t1 %>% mutate(str_locate(x, "de")[1])
bb
# A tibble: 2 x 2
  x      `str_locate(x, "de")[1]`
  <chr>                     <int>
1 aaded                         3
2 dedere                        3

Upvotes: 1

Views: 743

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

You are incorrectly indexing.

You are only subsetting 1st value which is recycled for rest of the columns.

library(dplyr)
library(stringr)

t1 %>% mutate(start = str_locate(x, "de")[, 1])

#  x      start
#  <chr>  <int>
#1 aaded      3
#2 dedere     1

Upvotes: 2

Related Questions