Can I find position in R avoiding the loop?

This is the question "R":

Suppose I have a three-letter vector, for example: “BBSSHHSRBSBBS,” which I like to find is the position of the first “S” that appears after the sequence “B”. For example, in the vector above, the first “S” that appears after the sequences “B” will appear in 3rd place of 10th place and last place (13)

I can do it trivially with loops, but I like to find out if there is a way to do this in "R" without looping at all.

The function should receive the vector R as input and return the position vector "S" as the output

Thanks,

+4
source share
4 answers

Another basic solution R

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

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

+7
source

Perhaps 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 
+4
source

in the database R.

 s <- "BBSSHHSRBSBBS" sl <- strsplit(s, 'BS')[[1]] pos <- nchar(sl[1]) + 2 # to get the S, 1 to get the B 
+3
source

This version also works for input type "BHHS"

 s1 <- "BBSSHHSRBSBBS" s2 <- "BHHS" spos <- function (s) { pat <- "B[^S]*(S)" m <- gregexpr(pat,s, perl=TRUE) as.vector(attr(m[[1]], "capture.start")) } spos(s1) spos(s2) 
+2
source

Source: https://habr.com/ru/post/1400749/


All Articles