R remove first character from string

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

Removing first and last characters.


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"

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)

Tags:

Regex

R