String manipulation basically refers to the process of handling and analyzing strings. It involves various operations concerned with modification and parsing of strings to use and change its data. R offers a series of in-built functions to manipulate the contents of a string. In this article, we will study different functions concerned with the manipulation of strings in R.
Concatenation of Strings
String Concatenation is the technique of combining two strings. String Concatenation can be done using many ways:
- paste() function Any number of strings can be concatenated together using the paste() function to form a larger string. This function takes separator as argument which is used between the individual string elements and another argument ‘collapse’ which reflects if we wish to print the strings together as a single larger string. By default, the value of collapse is NULL. Syntax:
paste(..., sep=" ", collapse = NULL)
Python3
str <- paste("Learn", "Code")
print (str)
|
"Learn Code"
- In case no separator is specified the default separator ” ” is inserted between individual strings. Example:
Python3
str <- paste(c(1:3), "4", sep = ":")
print (str)
|
"1:4" "2:4" "3:4"
- Since, the objects to be concatenated are of different lengths, a repetition of the string of smaller length is applied with the other input strings. The first string is a sequence of 1, 2, 3 which is then individually concatenated with the other string “4” using separator ‘:’.
Python3
str <- paste(c(1:4), c(5:8), sep = "--")
print (str)
|
"1--5" "2--6" "3--7" "4--8"
- Since, both the strings are of the same length, the corresponding elements of both are concatenated, that is the first element of the first string is concatenated with the first element of second-string using the sep ‘–‘.
- cat() function Different types of strings can be concatenated together using the cat()) function in R, where sep specifies the separator to give between the strings and file name, in case we wish to write the contents onto a file. Syntax:
cat(..., sep=" ", file)
Python3
str <- cat("learn", "code", "tech", sep = ":")
print (str)
|
learn:code:techNULL
- The output string is printed without any quotes and the default separator is ‘:’.NULL value is appended at the end. Example:
Python3
cat(c(1:5), file ='sample.txt')
|
1 2 3 4 5
The output is written to a text file sample.txt in the same working directory.
Calculating Length of strings
- length() function The length() function determines the number of strings specified in the function. Example:
Python3
print (length(c("Learn to", "Code")))
|
2
- There are two strings specified in the function.
- nchar() function nchar() counts the number of characters in each of the strings specified as arguments to the function individually. Example:
Python3
print (nchar(c("Learn", "Code")))
|
5 4
- The output indicates the length of Learn and then Code separated by ” ” .
Case Conversion of strings
- Conversion to upper case All the characters of the strings specified are converted to upper case. Example:
Python3
print (toupper(c("Learn Code", "hI")))
|
"LEARN CODE" "HI"
- Conversion to lower case All the characters of the strings specified are converted to lower case. Example:
Python3
print (tolower(c("Learn Code", "hI")))
|
"learn code" "hi"
- casefold() function All the characters of the strings specified are converted to lowercase or uppercase according to the arguments in casefold(…, upper=TRUE). Examples:
Python3
print (casefold(c("Learn Code", "hI")))
|
"learn code" "hi"
- By default, the strings get converted to lower case.
Python3
print (casefold(c("Learn Code", "hI"), upper = TRUE))
|
"LEARN CODE" "HI"
Character replacement
Characters can be translated using the chartr(oldchar, newchar, …) function in R, where every instance of old character is replaced by the new character in the specified set of strings. Example 1:
Python3
chartr("a", "A", "An honest man gave that")
|
Output:
"An honest mAn gAve thAt"
Every instance of ‘a’ is replaced by ‘A’. Example 2:
Output:
"Th#@ #@ #t" "It #@ great"
Every instance of old string is replaced by new specified string. “i” is replaced by “#” by “s” by “@”, that is the corresponding positions of old string is replaced by new string. Example 3:
Output:
Error in chartr("ate", "#@", "I hate ate") : 'old' is longer than 'new'
Execution halted
The length of the old string should be less than the new string.
Splitting the string
A string can be split into corresponding individual strings using ” ” the default separator. Example:
Python3
strsplit("Learn Code Teach !", " ")
|
Output:
[1] "Learn" "Code" "Teach" "!"
Working with substrings
substr(…, start, end) or substring(…, start, end) function in R extracts substrings out of a string beginning with the start index and ending with the end index. It also replaces the specified substring with a new set of characters. Example:
Python3
substr("Learn Code Tech", 1, 4)
|
Output:
"Lear"
Extracts the first four characters from the string.
Python3
str & lt
- c(& quot
program", & quot
with"
, & quot
new"
, & quot
language"
)
substr(str, 3, 3) & lt
- & quot
% & quot
print(str)
|
Output:
"pr%gram" "wi%h" "ne%" "la%guage"
Replaces the third character of every string with % sign.
Python3
str <- c("program", "with", "new", "language")
substr(str, 3, 3) <- c("%", "@")
print(str)
|
Output:
"pr%gram" "wi@h" "ne%" "la@guage"
Replaces the third character of each string alternatively with the specified symbols.
Similar Reads
R Version Information
R is a widely used programming language and software environment for statistical computing and graphics. It provides a wide variety of statistical and graphical techniques, including linear and nonlinear modeling, time-series analysis, classification, clustering, and more. R Programming Language is
2 min read
How to perform multiplication in R
Multiplication is a fundamental arithmetic operation that is essential in various fields, including data analysis, statistics, and machine learning. The R Programming Language provides robust support for performing multiplication, whether it's simple scalar multiplication, element-wise multiplicatio
3 min read
Introduction to R Studio
R Studio is an integrated development environment(IDE) for R. IDE is a GUI, where you can write your quotes, see the results and also see the variables that are generated during the course of programming. R Studio is available as both Open source and Commercial software.R Studio is also available a
4 min read
Row wise operation in R using Dplyr
The dplyr package in R programming is used to perform simulations in the data by performing manipulations and transformations. It can be installed into the working space using the following command : install.packages("dplyr")Create Dataframe using Row The data frame created by tibble contains rows a
4 min read
Mathematical Computations Using R
R Programming Language is widely used for statistical computing and data analysis. One of its core strengths lies in its ability to perform various mathematical computations efficiently. Here, we'll explore different methods and functions available in R for mathematical operations. 1. Basic Arithmet
3 min read
Iterating Over Characters of a String in R
In R Language a string is essentially a sequence of characters. Iterating over each character in a string can be useful in various scenarios, such as analyzing text, modifying individual characters, or applying custom functions to each character. This article covers different methods to iterate over
3 min read
Graph Plotting in R Programming
When it comes to interpreting the world and the enormous amount of data it is producing on a daily basis, Data Visualization becomes the most desirable way. Rather than screening huge Excel sheets, it is always better to visualize that data through charts and graphs, to gain meaningful insights. R -
5 min read
Hypothesis Testing in R Programming
A hypothesis is made by the researchers about the data collected for any experiment or data set. A hypothesis is an assumption made by the researchers that are not mandatory true. In simple words, a hypothesis is a decision taken by the researchers based on the data of the population collected. Hypo
6 min read
Saving Graphs as Files in R
In this article, we are going to learn how to save graphs to files in the R programming language. R Saving Graphs as Files Graphs are descriptive R objects which facilitate the visual representation of data in R. The data points become more understandable and readable when expressed in the form of p
4 min read
Raster Data in R
In this article we will discuss what is Raster Data in R Programming Language and how we use Raster Data in different work scenarios. What is Raster Data in R?Raster data, representing spatial data in a grid format, is crucial in fields such as geography, environmental science, and remote sensing. R
3 min read