1

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.

1 Answer 1

1

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.