How to replace a specific character?
1
1
Entering edit mode
2.1 years ago
yeluo ▴ 40

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 • 819 views
ADD COMMENT
3
Entering edit mode
2.1 years ago
yeluo ▴ 40

Fortunately, I find the way to solve it.

Here is the answer:

gsub("(^Stage.*)(A|B)","\\\\1", stri, perl = TRUE)
ADD COMMENT
1
Entering edit mode

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).

ADD REPLY
0
Entering edit mode

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

ADD REPLY

Login before adding your answer.

Traffic: 2597 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6