adam.888
adam.888

Reputation: 7846

R remove first character from string

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.

Upvotes: 28

Views: 131046

Answers (3)

David Mas
David Mas

Reputation: 1219

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)

Upvotes: 9

akrun
akrun

Reputation: 887971

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"

Upvotes: 50

dikesh
dikesh

Reputation: 3125

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

Removing first and last characters.

Upvotes: 26

Related Questions