This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to replace a specific character?

I have the vector:

stri = c("Stage II", "Stage IVA", "Stage IIIB", "ACB" )

and I want to remove the A and B in "Stage IVA" ,"Stage IIIB", but not in "ACB",

I want to get

c("Stage II", "Stage IV", "Stage III", "ACB" )

Is there any method by using gsub?

gsub regex r

1 answer

Fortunately, I find the way to solve it.

Here is the answer:

gsub("(^Stage.*)(A|B)","\\\\1", stri, perl = TRUE)

You can have it simpler: gsub("A$|B$", "", c("Stage II" , "Stage IVA" ,"Stage IIIB" ,"ACB" ))

That reads as "replace all A's and B's if they're the trailing character (that is what $ means, so last character).

Also, I recommend replacing whitespaces with something like underscore to have syntactically correct names in R.

Log in to answer this question.