Remove Last Character From String in R

Manav Narula Jan 09, 2021
  1. Use the substr() Function to Remove the Last Characters in R
  2. Use the str_sub() Function to Remove the Last Characters in R
  3. Use the gsub() Function to Remove the Last Characters in R
Remove Last Character From String in R

A string is an essential and common part of any programming language. It is essentially a collection of characters in a sequence and can store variables and constants.

In R, anything between single or double quotes is considered a string. This tutorial will introduce how to remove the last characters from a string or a string vector.

Use the substr() Function to Remove the Last Characters in R

The substr() function in R extracts or replaces a substring from a string. We pass the given string and the starting and final position of the required substring to the function. See the following example.

substr("Jack",2,3)
[1] "ac"

In the above example, it extracts characters from the 2nd to third 3rd position.

name <- "Jack"
substr(name,1,nchar(name)-2)
[1] "Ja"

The nchar() function returns the string’s length so that 1, nchar(name)-2 specifies the substring range from the beginning to the third last character. The above example code removes the last two characters from the given string.

We can also pass a string vector or a column name to the substr() function. The code below will show how we can remove the last two characters from a string vector:

name <- c("Jackkk","Markkk","Jayyy")
substr(name,1,nchar(name)-2)
"Jack" "Mark" "Jay"

Use the str_sub() Function to Remove the Last Characters in R

The str_sub() function is provided in the stringr package in R. It is very similar to the substr() function with a few differences. Unlike the substr() function, it already has some default arguments and deals with negative indices differently.

We can remove the last two characters using the str_sub() functions shown below:

library(stringr)
name <- c("Jackkk","Markkk","Jayyy")
str_sub(name,1,nchar(name)-2)
[1] "Jack" "Mark" "Jay"

Use the gsub() Function to Remove the Last Characters in R

The gsub() function in R replaces or extracts strings by matching a specific pattern. To remove characters from the end using the gsub() function, we need to use regular expressions. See the following example.

name <- c("Jackkk","Markkk","Jayyy")
gsub('.{2}$', '', name)
[1] "Jack" "Mark" "Jay" 

The .{2}$ is the regular expression that matches the last two characters. . matches any character, {2} matches the pattern before it twice, and $ matches the end of the string.

Author: Manav Narula
Manav Narula avatar Manav Narula avatar

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

LinkedIn

Related Article - R String