Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R remove first character from string

Tags:

regex

r

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.

like image 751
adam.888 Avatar asked Jan 31 '16 11:01

adam.888


People also ask

How do I remove the first character of a string in R?

If we need to remove the first character, use sub , match one character ( . represents a single character), replace it with '' . Or for the first and last character, match the character at the start of the string ( ^. ) or the end of the string ( .

How do I remove the first character from a column in R?

To remove first character from column name in R data frame, we can use str_sub function of stringr package.

How do you extract the first 5 characters from the string str?

You can use the substr function like this: echo substr($myStr, 0, 5); The second argument to substr is from what position what you want to start and third arguments is for how many characters you want to return.

How do I extract a letter from a string in R?

The substring function in R can be used either to extract parts of character strings, or to change the values of parts of character strings. substring of a vector or column in R can be extracted using substr() function. To extract the substring of the column in R we use functions like substr() and substring().


2 Answers

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"
like image 97
akrun Avatar answered Sep 19 '22 12:09

akrun


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

Removing first and last characters.

like image 33
dikesh Avatar answered Sep 18 '22 12:09

dikesh