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 CAR10100231191000C
and 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
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.
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.
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.
You can use sub
for this:
sub('C$', '', v1)
Which removes the letter C
from the last position in the string if it exists.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With