libby
libby

Reputation: 634

R string matching and replace

Starting with the string -theta[0] * x[0] * x[4] -theta[1] * x[1], I'd like capture theta[.] and replace with exp(theta[.]) giving the final result as:

-exp(theta[0]) * x[0] * x[4] -exp(theta[1]) * x[1]

How do I accomplish this in R?

I tried the following to test by matching between as as follows:

p <- c("abba", "abcdab")                                                      
gsub("\\(a[^a]*a\\)", "|\\1|", p)

I expected the output to be something like

|abba|
|abcda|b

But the output is

[1] "abba"   "abcdab"

What is the proper regex expression to achieve the desired result?

Thanks in advance.

Upvotes: 1

Views: 75

Answers (1)

Julius Vainora
Julius Vainora

Reputation: 48211

We may use

gsub("(theta\\[\\d+\\])", "exp(\\1)", "-theta[0] * x[0] * x[4] -theta[1] * x[1]")
# [1] "-exp(theta[0]) * x[0] * x[4] -exp(theta[1]) * x[1]"

it matches theta[.] with any number of digits in the place of . and replaces it by exp(theta[.]).

Your attempt was good, you just didn't need to escape the brackets as they signify the group that you want to refer to later:

gsub("(a[^a]*a)", "|\\1|", p)
# [1] "|abba|"   "|abcda|b"

Upvotes: 1

Related Questions