Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can I find position in R while avoiding looping?

Tags:

r

This is an "R" question:

suppose I have a vector of 3 letters for example: "BBSSHHSRBSBBS" what I like to find is the position of the first "S" that appears after "B" sequence. For example in the vector above the first "S" that appears after "B" sequences will appear in the 3-rd place the 10-th place and the last place(13)

I can do trivially using loops but I like to find out if there is any way to do it in "R" without looping at all.

The function should get an R vector as an input and return the vector of "S" positions as an output

Thanks,

like image 646
user1261321 Avatar asked Dec 04 '22 17:12

user1261321


2 Answers

Another base R solution

str <- "BBSSHHSRBSBBS"
pos <- unlist(gregexpr("BS", str))

Note that gregexpr accepts regular expressions so you can catch much more complex patterns.

like image 62
nico Avatar answered Dec 08 '22 15:12

nico


Maybe with str_locate_all:

library(stringr)
v <- "BBSSHHSRBSBBS"
str_locate_all(v, "BS")
[[1]]
     start end
[1,]     2   3
[2,]     9  10
[3,]    12  13
like image 22
johannes Avatar answered Dec 08 '22 14:12

johannes