1

I want to insert a specific character ("+") in front of the character "b" as part of a string in R. So for example "2b^3" should be converted to "2+b^3" or "200b" to "200+b". How can I achieve this?

Edit: I have a follow up question to the one before:

I have tried this answer: Extract a substring according to a pattern

But it doesn't work for ^:

string = "2+b^3"
sub(".*^", "", string)

gives me still "2+b^3" and I would like to receive "3".

What can I do?

dlwhch
  • 157
  • 7

2 Answers2

1

A possible solution, in base R:

gsub("b", "+b", "2b^3")

#> [1] "2+b^3"

Or using stringr::replace:

stringr::str_replace("2b^3", "b", "+b")

#> [1] "2+b^3"
PaulS
  • 21,159
  • 2
  • 9
  • 26
1

If the b char is always prepended by a digit, you can capture the digits and use the capture group in the replacement.

gsub("(\\d)b", "\\1+b", "2b^3")

Output (R demo)

[1] "2+b^3"

For the second part you have to escape the caret \^ or else it would denote the start of the string.

string = "2+b^3"
sub(".*\\^", "", string)

Output (R demo)

3
The fourth bird
  • 154,723
  • 16
  • 55
  • 70