Question: 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`?

Answer: 
```
lapply( dfrm, function(col_) {gsub( "R","",col_)} )

```
If you want to remove *all* occurrences of the specific character at the end of string, you may want to use

```r
x <- c("EC02", "502R", "603RR")
sub("R+$", "", x)
# => [1] "EC02" "502"  "603" 
trimws(x, which="right", whitespace="R+")
# => [1] "EC02" "502"  "603" 

```

See the [R demo](https://tio.run/##K/r/v0LBRlchWUPJ1dnASElHQcnUwCgIRJsZGAcFKWlyFZcmaSgFaauAxIC4QpNLWcHWTiHaMFYBogesRUkBrENJgaukKDO3vFijQkehPCMzOcNWqSgzPaNECcwtSS0uSExOtQWap0TAnP//AQ). *Notes*:

* `sub("R+$", "", x)` - one or more (`+`) `R` letters at the end of string (`$`) are matched once (`sub` matches only the first occurrence of the pattern) and replaces them with an empty string
* `trimws(x, which="right", whitespace="R+")` - one or more `R`s (`R+`) are matched at the end of the string (`which="right"`) and removed (`trimws` is basically using `sub` under the hood).

**NOTE 2**: If you plan to remove special regex metacharacters this way you will need to escape them. The chars that need escaping are:

```none
$^*()+\[{.?

```

For example:

```r
sub("\\$+$", "", x) # Remove all $ chars at the end of string
sub("\\^+$", "", x) # Remove all ^ chars at the end of string
sub("\\(+$", "", x) # Remove all ( chars at the end of string
sub("\\)+$", "", x) # Remove all ) chars at the end of string
sub("\\++$", "", x) # Remove all + chars at the end of string
sub("\\[+$", "", x) # Remove all [ chars at the end of string
sub("\\{+$", "", x) # Remove all { chars at the end of string
sub("\\.+$", "", x) # Remove all . (dot) chars at the end of string
sub("\\?+$", "", x) # Remove all ? chars at the end of string

```