Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove specific last character from string

Tags:

regex

r

gsub

I have following string vector:

 EC02   502R   603           515    602   
 KL07   601    511R   505R   506R   503   
 508    514    501    509R   510    501R  
 512R   516    507    604    502    601R  
 SPK01  504    504R   ACK01  503R   508R  
 507R   ACK03  513    EC01   506    ECH01 
 ACK02  SPK02  509    511    512    505   
 KA01   RS01   510R   SKL01  SPK03  603R  
 602R   604R   513R   AECH01 ER03   AECH02
 RS02   514R   ER01   RH01   AR05   RH02  
 515R   ER02   M01 

I want to replace 502R to 502, 501R to 501, 503R to 503 and so on...

Only character R has to be replaced which is occurring at the end of the string.

How can I do it with gsub?

like image 851
Neil Avatar asked Jul 24 '17 03:07

Neil


People also ask

How do I remove a specific character from a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do I remove the last word from a string in Java?

The idea is to use the deleteCharAt() method of StringBuilder class to remove first and the last character of a string. The deleteCharAt() method accepts a parameter as an index of the character you want to remove.

How do I remove one character from a string in Java?

Use the deleteCharAt Method to Remove a Character From String in Java. The deleteCharAt() method is a member method of the StringBuilder class that can also be used to remove a character from a string in Java.


2 Answers

If you have a string vector and want to replace the last R character from it you can use sub. $ here ensures that the R is the last character in your vector.

sub("R$", "", str)

#[1] "EC02"  "502"   "603"   "5RFRS"

data

str <- c("EC02", "502R","603", "5RFRS)

I have used sub here instead of gsub. sub replaces only first occurrence of the pattern whereas gsub replaces all occurrences of the pattern though in this case the usage of sub/gsub wouldn't matter.

like image 178
Ronak Shah Avatar answered Oct 11 '22 15:10

Ronak Shah


lapply( dfrm, function(col_) {gsub( "R","",col_)} )
like image 34
IRTFM Avatar answered Oct 11 '22 15:10

IRTFM