Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 966
Duck Avatar asked Sep 03 '13 20:09

Duck


People also ask

How do I remove a character from a string variable?

We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.

Can you delete characters from a string?

You can remove a character or multiple characters from a string using replace() or translate(). Both the replace() and translate() methods return the same outcome: a string without the characters you have specified.

How do I remove special characters from a column name in R?

To remove a character in an R data frame column, we can use gsub function which will replace the character with blank. For example, if we have a data frame called df that contains a character column say x which has a character ID in each value then it can be removed by using the command gsub("ID","",as.


1 Answers

You can use sub for this:

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

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

like image 74
Justin Avatar answered Nov 08 '22 11:11

Justin