Jin Niu
Jin Niu

Reputation: 3

How can I get rid of specific parenthesis without losing their contents?

I am trying to get rid of the parentheses for params(#) in a long string with gsub in R.

From:

"(Prot) = ((1-(BTZ)^params(9)/((BTZ)^params(9)+params(10)^params(9))*(1+params(10)^params(9)))-(Prot)) / params(8)"

to get the result of:

"(Prot) = ((1-(BTZ)^params9/((BTZ)^params9+params10^params9)*(1+params10^params9))-(Prot)) / params8"

But I cannot get the right number out of the parentheses. I tried this:

gsub( "params\\(\\d\\)" ,'params\\d', j , fixed = FALSE)

This is what i got:

"(Prot) = ((1-(BTZ)^paramsd/((BTZ)^paramsd+params(10)^paramsd)*(1+params(10)^paramsd))-(Prot)) / paramsd;"

Upvotes: 0

Views: 34

Answers (1)

user10191355
user10191355

Reputation:

You need to include a capture group in your pattern using () and a reference to the capture group in replacement using \\1:

gsub("\\((\\d+)\\)", "\\1", j)

#### OUTPUT ####
"(Prot) = ((1-(BTZ)^params9/((BTZ)^params9+params10^params9)*(1+params10^params9))-(Prot)) / params8"

I've also included + for cases where there's more than one digit (e.g. "10").

Upvotes: 4

Related Questions