24

I can remove the last character from a string:

listfruit  <- c("aapplea","bbananab","oranggeo")
gsub('.{1}$', '', listfruit)

But I am having problems trying to remove the first character from a string. And also the first and last character. I would be grateful for your help.

0

3 Answers 3

41

If we need to remove the first character, use sub, match one character (. represents a single character), replace it with ''.

sub('.', '', listfruit)
#[1] "applea"  "bananab" "ranggeo"

Or for the first and last character, match the character at the start of the string (^.) or the end of the string (.$) and replace it with ''.

gsub('^.|.$', '', listfruit)
#[1] "apple"  "banana" "rangge"

We can also capture it as a group and replace with the backreference.

sub('^.(.*).$', '\\1', listfruit)
#[1] "apple"  "banana" "rangge"

Another option is with substr

substr(listfruit, 2, nchar(listfruit)-1)
#[1] "apple"  "banana" "rangge"
25
library(stringr)
str_sub(listfruit, 2, -2)
#[1] "apple"  "banana" "rangge"

Removing first and last characters.

9

For me performance was important so I run a quick benchmark with the available solutions.

library(magrittr)
comb_letters = combn(letters,5) %>% apply(2, paste0,collapse = "")

bench::mark(
  gsub = {gsub(pattern = '^.|.$',replacement = '',x = comb_letters)},
  substr = {substr(comb_letters,start = 2,stop = nchar(comb_letters) - 1)},
  str_sub = {stringr::str_sub(comb_letters,start =  2,end = -2)}
)
#> # A tibble: 3 x 6
#>   expression      min   median `itr/sec` mem_alloc `gc/sec`
#>   <bch:expr> <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl>
#> 1 gsub         32.9ms   33.7ms      29.7  513.95KB     0   
#> 2 substr      15.07ms  15.84ms      62.7    1.51MB     2.09
#> 3 str_sub      5.08ms   5.36ms     177.   529.34KB     2.06

Created on 2019-12-30 by the reprex package (v0.3.0)

1
  • 2
    If anyone has problems installing stringr package, use stringi::stri_sub instead.
    – Adrià
    Jul 24, 2020 at 10:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.