Table of Contents
To remove the last character from a string in R, you can use either the substr() or substring() functions. With substr(), you can use the nchar() function to specify the length of the string, subtract 1 to remove the last character, and then use that value to specify the length of the substring. With substring(), you can use the nchar() function to calculate the length of the string, subtract 1 to remove the last character, and then use that value to specify the end position of the substring.
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 <- data.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 function from the stringr package:
library(stringr) #remove last character from each string in 'name' column df$name <- str_sub(df$name, end = -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.
The following tutorials explain how to perform other common tasks in R: