Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positive look ahead in R - passing variables

Tags:

variables

regex

r

I got stuck in a regular expression. I usually use this line of code to find overlapping repetitions in strings:

gregexpr("(?=ATGGGCT)",text,perl=TRUE)
[[1]]
[1]  16  45  52  75 203 210 266 273 327 364 436 443 480 506 534 570 649
attr(,"match.length")
[1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
attr(,"useBytes")
[1] TRUE

Now I want to give to gregexpr a pattern contained in a variable:

x="GGC"

and of course if I pass the variable x, gregexpr is going to search "x" and not what the variable contains

gregexpr("(?=x)",text,perl=TRUE)
[[1]]
[1] -1
attr(,"match.length")
[1] -1
attr(,"useBytes")
[1] TRUE

How can I pass my variable to gregexpr in this case of positive look ahead?

like image 347
Valentina Avatar asked Dec 15 '22 19:12

Valentina


1 Answers

I'd play with the sprintf function:

x <- "AGA"
text <- "ACAGAGACTTTAGATAGAGAAGA"
gregexpr(sprintf("(?=%s)", x), text, perl=TRUE)
## [[1]]
## [1]  3  5 12 16 18 21
## attr(,"match.length")
## [1] 0 0 0 0 0 0
## attr(,"useBytes")
## [1] TRUE

sprintf substitutes the occurrence of %s by the value of x.

like image 85
gagolews Avatar answered Jan 02 '23 18:01

gagolews