Extract First or Last n Characters from String in R
Last Updated :
01 May, 2022
In this article, we will know how to extract the last and first char from a given string in the R programming language.
For the example purpose, "Geeks for Geeks is Great" is included in our example string. Let's take a look at how we can extract the first and last n characters of this example string.
Example 1: In R, extract the first n characters from a string:
We will learn how to obtain the first n characters of a string in the first example. We can use the substr function for this task:
In the below example, you can see that the substr function returned this to the RStudio console (i.e. the first three characters). To use the substr command to extract the first n characters, we are required to specify three values within the function:
- The string of characters (in our case x).
- We want to maintain the first character (in our case 1).
- The final character we wish to maintain is (in this specific example we extracted the first 3 values).
R
x <- "Geeks for Geeks is Great!"
# Extract first 4 letters
substr(x, 1, 4)
Example 2: In Base R, extract the last n characters from a string:
Here, we will also utilize the substr function in the second example (as in Example 1). However, the code is becoming a little more complicated this time:
Based on the previous result, we can see that we have extracted the characters ple, i.e. the last three characters of our example string. To do so, we have to supply three inputs for the substr function once more:
- The string of characters (in our case x).
- We want to maintain the first character.
- To begin, we have to utilize the nchar function to determine the length of our string (i.e. nchar(x)).
- Then we needed to deduct the number of characters we wanted to extract from the length of our string (i.e. nchar(x) – n last).
- We had to add the value 1 to our computation since we needed to specify the starting character with the substr function (i.e. nchar(x) – n last + 1).
- The last character we wish to maintain (in this example, the last character of our string, nchar(x)).
This code works correctly, although it is admittedly more difficult than the code in Example 1. As a result, in the next example, I'll show you a simpler way of extracting the final n characters of a string.
R
x <- "Geeks for Geeks is Great!"
# Extract last six characters
n_last <- 6
substr(x, nchar(x) - n_last + 1, nchar(x))
Example 3: Using the stringr Package in R, extract the last n characters from a string:
The stringr R package makes it simple to get the last n characters of a string. First, let's install and load the package.
Syntax to install and install the stringr package in the R console:
install.packages("stringr")
library("stringr")
Str_sub() function: This will recycle all arguments to be the same length as the longest argument. If any arguments are of length 0, the output will be a zero length character vector
Syntax: str_sub(string, start = 1L, end = -1L)
Parameters:
- string: input character vector.
- start, end: Two integer vectors. start gives the position of the first character (defaults to first), end gives the position of the last (defaults to last character). Alternatively, pass a two-column matrix to start.Negative values count backwards from the last character.
In this example, we are simply calling the str_sub() function with the string and the first and the end position accordingly to get extract the last n characters from a string in the R programming language.
R
x <- "Geeks for Geeks is Great!"
install.packages("stringr")
library("stringr")
str_sub(x, - 3, - 1)
Similar Reads
Extract Numbers from Character String Vector in R
In this article, we are going to see how to extract Numbers from Character String Vector in R Programming Language. There are different approaches to extract numbers from character string vectors using some in-built functions. It can be done in the following ways:Using the gsub() functionUsing the g
2 min read
Extract first N rows from dataframe in R
A required number of rows can be retrieved from a dataframe for some computation that demands so. In this article, we will be discussing two different approaches for extracting the first n rows from the data frame File in Use: Method 1: Using head() function This function will help to extract the gi
1 min read
Count Number of Characters in String in R
In this article, we are going to see how to get the number of characters in a string in R Programming Language. The number of characters in a string refers to the length of the string.Examples:Input: GeeksforgeeksOutput: 13Explanation: Total 13 characters in the given string.Input: Hello worldOutput
2 min read
Remove Newline from Character String in R
In this article, we are going to see how to remove the new line from a character string in R Programming Language. Example: Input: String with newline: "Hello\nGeeks\rFor\r\n Geeks" Output: String after removing new line: "HelloGeeksFor Geeks"Method 1: Using gsub() function gsub() function in R Lang
2 min read
How to Check if Characters are Present in a String in R.
In this article, we will learn how to check the presence of a character, substring or number in a string using R Programming Language. This can be useful for tasks where we want to filter data, pattern matching or data cleaning. We generally use grepl() function, a versatile tool that is used for ch
6 min read
Remove All Special Characters from String in R
In this article, we are going to remove all special characters from strings in R Programming language. For this, we will use the str_replace_all() method to remove non-alphanumeric and punctuations which is available in stringr package. Installation To install this library type the below command in
1 min read
Concatenate Vector of Character Strings in R
In this article, we will discuss how to concatenate the strings present in two or more vectors in R Programming Language. Discussed below are various methods of doing so. Method 1: Using paste() paste() function is used to combine strings present in vectors passed to it  an argument. Syntax: paste(
4 min read
How to Convert Character to Factor in R?
The as.factor() method in R Programming Language is used to convert the character vector to factor class. Converting Character Vector To Factor Syntax: as.factor(char-vec) where char-vec is the character vector The class indicative of the data type of the vector can be obtained using the class() me
2 min read
Repeat Character String N Times in R
In this article, we will discuss how to repeat the character string N times in the R programming language. Character string means a set of characters . Example: "Hello Geek","Python","Languages_Python" are some examples Method 1: Using replicate() method This function used to give n replicas from th
3 min read
Convert Character Matrix to Numeric Matrix in R
In this article, we are going to see how to convert a given character matrix to numeric in R Programming Language. Converting the Character Matrix to Numeric Matrix we will use as.numeric() & matrix() Functions. Functions Usedas.numeric() function: This function is used to convert a given column
3 min read