Duck
Duck

Reputation: 39595

How to remove a character in a variable of string type in R

Hi dear I have a variable of this type in R:

v1
CAR10100231095000C 
CAR10100231189000 
CAR10100231191000C 
CAR10100231192000 
CAR10100231194000C 
CAR101002311950002 
CAR101002311960001 

My problem is with rows that have a C as last element of the observation. I was trying to use nchar() function but I have others rows that have the same length for example CAR10100231191000Cand CAR101002311960001. My problem is how to remove C from raws with this character and get a new variable of this form:

v1
CAR10100231095000 
CAR10100231189000 
CAR10100231191000 
CAR10100231192000 
CAR10100231194000 
CAR101002311950002 
CAR101002311960001 

Where Cs were removed from rows that have and the rest of the rows have their original form. Thanks

Upvotes: 9

Views: 12555

Answers (1)

Justin
Justin

Reputation: 43245

You can use sub for this:

sub('C$', '', v1)

Which removes the letter C from the last position in the string if it exists.

Upvotes: 16

Related Questions