Home > front end >  Insert specific character in front of specific pattern in R
Insert specific character in front of specific pattern in R

Time:06-06

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?

CodePudding user response:

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"

CodePudding user response:

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
  • Related