Home » How to Remove Last Character from String in R (2 Examples)

How to Remove Last Character from String in R (2 Examples)

by Erma Khan

You can use the following methods to remove the last character from each string in a vector in R:

Method 1: Remove Last Character Using Base R

substr(df$some_column, 1, nchar(df$some_column)-1)

Method 2: Remove Last Character Using stringr Package

library(stringr) 

str_sub(df$some_column, end = -2)

The following examples show how to use each method with the following data frame in R:

#create data frame
df frame(name=c('Andy', 'Bert', 'Chad', 'Derrick', 'Eric', 'Fred'),
                 sales=c(18, 22, 19, 14, 14, 11))

#view data frame
df

     name sales
1    Andy    18
2    Bert    22
3    Chad    19
4 Derrick    14
5    Eric    14
6    Fred    11

Example 1: Remove Last Character Using Base R

The following code shows how to remove the last character from each string in the name column of the data frame:

#remove last character from each string in 'name' column
df$name = substr(df$name, 1, nchar(df$name)-1)

#view updated data frame
df

    name sales
1    And    18
2    Ber    22
3    Cha    19
4 Derric    14
5    Eri    14
6    Fre    11

Notice that the last character from each string in the name column has been removed.

Example 2: Remove Last Character Using stringr Package

The following code shows how to remove the last character from each string in the name column of the data frame by using the str_sub() function from the stringr package:

library(stringr)

#remove last character from each string in 'name' column
df$name -2)

#view updated data frame
df

    name sales
1    And    18
2    Ber    22
3    Cha    19
4 Derric    14
5    Eri    14
6    Fre    11

Notice that the last character from each string in the name column has been removed.

Note that this method produces identical results to the previous method.

However, if you’re working with an extremely large data frame then str_sub() is likely to be faster than the substr() function from base R.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Recode Values Using dplyr
How to Replace NA with Zero in dplyr
How to Filter Rows that Contain a Certain String Using dplyr

Related Posts