Module 4 R
Module 4 R
Data Manipulation
Data manipulation involves modifying data to make it easier to read and to be more
organized. We manipulate data for analysis and visualization. It is also used with the term
‘data exploration’ which involves organizing data using available sets of variables.
At times, the data collection process done by machines involves a lot of errors and
inaccuracies in reading. Data manipulation is also used to remove these inaccuracies and
make data more accurate and precise.
So to use the data manipulation function, first need to import the dplyr package
using library(dplyr) line of code. Below is the list of a few data manipulation functions
present in dplyr package.
filter() method
The filter() function is used to produce the subset of the data that satisfies the condition
specified in the filter() method. In the condition, we can use conditional operators, logical
operators, NA values, range operators etc. to filter out data. Syntax of filter() function is
given below-
filter(dataframeName, condition)
Example:
In the below code we used filter() function to fetch the data of players who scored more
than 100 runs from the “stats” data frame.
Output
player runs wickets
1 B 200 20
2 C 408 NA
distinct() method
The distinct() method removes duplicate rows from data frame or based on the specified
columns. The syntax of distinct() method is given below-
distinct(dataframeName, col1, col2,.., .keep_all=TRUE)
Example:
Here in this example, we used distinct() method to remove the duplicate rows from the data
frame and also remove duplicates based on a specified column.
Output
player runs wickets
1 A 100 17
2 B 200 20
3 C 408 NA
4 D 19 5
5 A 56 2
player runs wickets
1 A 100 17
2 B 200 20
3 C 408 NA
4 D 19 5
arrange() method
In R, the arrange() method is used to order the rows based on a specified column. The
syntax of arrange() method is specified below-
arrange(dataframeName, columnName)
Example:
In the below code we ordered the data based on the runs from low to high using arrange()
function.
Output
player runs wickets
1 D 19 5
2 A 100 17
3 B 200 20
4 C 408 NA
select() method
The select() method is used to extract the required columns as a table by specifying the
required column names in select() method. The syntax of select() method is mentioned
below-
select(dataframeName, col1,col2,…)
Example:
Here in the below code we fetched the player, wickets column data only using select()
method.
# import dplyr package
library(dplyr)
Output
player wickets
1 A 17
2 B 20
3 C NA
4 D 5
rename() method
The rename() function is used to change the column names. This can be done by the below
syntax-
rename(dataframeName, newName=oldName)
Example:
In this example, we change the column name “runs” to “runs_scored” in stats data
frame.
Output
player runs_scored wickets
1 A 100 17
2 B 200 20
3 C 408 NA
4 D 19 5
mutate() & transmute() methods
These methods are used to create new variables. The mutate() function creates new
variables without dropping the old ones but transmute() function drops the old variables
and creates new variables. The syntax of both methods is mentioned below-
mutate(dataframeName, newVariable=formula)
transmute(dataframeName, newVariable=formula)
Example:
In this example, we created a new column avg using mutate() and transmute() methods.
Output
player runs wickets avg
1 A 100 17 25.00
2 B 200 20 50.00
3 C 408 7 102.00
4 D 19 5 4.75
avg
1 25.00
2 50.00
3 102.00
4 4.75
Here mutate() functions adds a new column for the existing data frame without dropping
the old ones where as transmute() function created a new variable but dropped all the old
columns.
summarize() method
Using the summarize method we can summarize the data in the data frame by using
aggregate functions like sum(), mean(), etc. The syntax of summarize() method is specified
below-
summarize(dataframeName, aggregate_function(columnName))
Example:
In the below code we presented the summarized data present in the runs column using
summarize() method.
# summarize method
summarize(stats, sum(runs), mean(runs))
Output
sum(runs) mean(runs)
1 727 181.75
The apply() collection is a part of R essential package. This family of functions helps us to
apply a certain function to a certain data frame, list, or vector and return the result as a list
or vector depending on the function we use. There are these following four types of
function in apply() function family:
apply() function
The apply() function lets us apply a function to the rows or columns of a matrix or data
frame. This function takes matrix or data frame as an argument along with function and
whether it has to be applied by row or column and returns the result in the form of a vector
or array or list of values obtained.
Syntax: apply( x, margin, function )
Parameters:
x: determines the input array including matrix.
margin: If the margin is 1 function is applied across row, if the margin is 2 it is
applied across the column.
function: determines the function that is to be applied on input data.
Example:
Here, is a basic example showcasing the use of apply() function along rows as well as
columns.
Output:
lapply() function
The lapply() function helps us in applying functions on list objects and returns a list object
of the same length. The lapply() function in the R Language takes a list, vector, or data
frame as input and gives output in the form of a list object. Since the lapply() function
applies a certain operation to all the elements of the list it doesn’t need a MARGIN.
Syntax: lapply( x, fun )
Parameters:
x: determines the input vector or an object.
fun: determines the function that is to be applied to input data.
Example:
Here, is a basic example showcasing the use of the lapply() function to a vector.
Output:
sapply() function
The sapply() function helps us in applying functions on a list, vector, or data frame and
returns an array or matrix object of the same length. The sapply() function in the R
Language takes a list, vector, or data frame as input and gives output in the form of an array
or matrix object. Since the sapply() function applies a certain operation to all the elements
of the object it doesn’t need a MARGIN. It is the same as lapply() with the only difference
being the type of return object.
Syntax: sapply( x, fun )
Parameters:
x: determines the input vector or an object.
fun: determines the function that is to be applied to input data.
Example:
Here, is a basic example showcasing the use of the sapply() function to a vector.
Output:
tapply() function
The tapply() helps us to compute statistical measures (mean, median, min, max, etc..) or a
self-written function operation for each factor variable in a vector. It helps us to create a
subset of a vector and then apply some functions to each of the subsets. For example, in an
organization, if we have data of salary of employees and we want to find the mean salary
for male and female, then we can use tapply() function with male and female as factor
variable gender.
Syntax: tapply( x, index, fun )
Parameters:
x: determines the input vector or an object.
index: determines the factor vector that helps us distinguish the data.
fun: determines the function that is to be applied to input data.
Example:
Here, is a basic example showcasing the use of the tapply() function on the diamonds
dataset which is provided by the tidyverse package library.
Output:
Aggregate() function is used to get the summary statistics of the data by group. The
statistics include mean, min, sum. max etc.
Syntax:
aggregate(dataframe$aggregate_column, list(dataframe$group_column), FUN)
where
dataframe is the input dataframe.
aggregate_column is the column to be aggregated in the dataframe.
group_column is the column to be grouped with FUN.
FUN represents sum/mean/min/ max.
Example : R program to create with 4 columns and group with subjects and get the average
(mean).
# display
print(data)
Output:
What is Plyr Package?
Plyr is a package for data manipulation in R that provides a set of functions for splitting,
applying, and combining data. It is based on the concept of split-apply-combine, where a
dataset is first split into smaller subsets, a function is applied to each subset, and the results
are then combined into a single output. This process is useful for tasks such as aggregating
data, summarizing data, and transforming data.
Before using the plyr package, it needs to be installed and loaded into R. The package can
be installed using the following command:
[Link]("plyr")
After the package is installed, it can be loaded into R using the following command:
library(plyr)
The ddply( ) function is a powerful tool for splitting data frames into smaller subsets,
applying a function to each subset, and then combining the results into a new data frame.
The name “ddply” stands for “split, apply, and combine”, which summarizes the three main
steps of the function. Here are the main arguments of ddply():
Syntax:
Parameters: `data`
object:The input data frame that you want to split and process.
Syntax:
Parameters: `variables`
object:One or more grouping variables that define how the data should be split.
Syntax:
Parameters: `fun`
object:A function that you want to apply to each subset of the data frame.
Syntax:
Parameters: `…`
object:Additional arguments that are passed to the function specified in [Link]’s an
example of how to use ddply() to calculate the mean miles per gallon (mpg) of cars in the
mtcars dataset, grouped by the number of cylinders in the engine:
library(plyr)
# Using ddply to group by number of cylinders and calculate mean mpg
ddply(mtcars, .(cyl), summarise, mean_mpg = mean(mpg))
In this example, ddply() is used to group the mtcars dataset by the cyl variable (number of
cylinders), and then the summarise() function is used to calculate the mean mpg for each
group. The resulting output is a data frame with two columns: cyl and mean_mpg.
The ldply() function is used to convert a list of data frames or vectors into a single data
frame, with each element of the list becoming a row of the output data frame. The name
“ldply” stands for “list and bind data frames”, which summarizes the main action of the
function. Finally, the ldply() function returns a data frame that contains all the elements of
the input list, stacked on top of each other. Here are the main arguments of ldply():
Syntax:
Parameters: `data`
object:The input list that you want to convert to a data frame.
Syntax:
Parameters: `.fun`
object:An optional function that you want to apply to each element of the list before
converting it to a data frame.
Syntax:
Parameters: `…`
object:Additional arguments that are passed to the function specified in .fun.
Example:
library(plyr)
# Create a list of data frames
countries_1 <- [Link](country = c("USA", "Canada", "Mexico"), population =
c(328, 37, 130))
countries_2 <- [Link](country = c("Brazil", "Argentina", "Chile"), population =
c(211, 45, 19))
countries_list <- list(countries_1, countries_2)
# Use ldply() to combine the list of data frames into a single data frame
combined_df <- ldply(countries_list, [Link])
# View the resulting data frame
combined_df
In this example, we first create a list of two data frames (countries_1 and countries_2) using
[Link]() function. Then, we combine these data frames into a list called countries_list.
Finally, we use ldply() function to combine all the data frames in countries_list into a single
data frame called combined_df. The resulting data frame contains information about all the
countries in the original data frames.
library(plyr)
# Create a sample matrix
mat <- matrix(1:9, nrow = 3)
# Display created matrix
mat
# Use adply() to calculate the sum of each row
result <- adply(mat, 1, function(x) sum(x))
# View the result
Result
In this example, the adply() function is used to apply the sum() function to each row of the
matrix mat. The second argument (1) specifies that we want to apply the function to each
subset of the array consisting of one row and all columns. The third argument is an
anonymous function that calculates the sum of each row. The resulting result data frame has
one column and three rows (one for each row in mat). The values in each row correspond to
the sum of that row.
join() is a function from the plyr package in R that is used to join two data frames by a
common column. The join() function takes several arguments, including:
Syntax:
Parameters: `x`, `y`
object: Data frames join.
Syntax:
Parameters: `by`
object: The column(s) to join the data frames .
Syntax:
Parameters: `type`
object: The type of join to perform (e.g. “inner”, “outer”, “left”, “right”).
Syntax:
Parameters: `suffix`
object:A character vector to append to overlapping variable names (defaults to c(“.x”,
“.y”))
Example:
library(plyr)
# Create two sample data frames
df1 <- [Link](
id = c(1, 2, 3),
name = c("Alice", "Bob", "Charlie")
)
df2 <- [Link](
id = c(2, 3, 4),
age = c(25, 30, 35)
)
# Print the created dataset
df1
df2
# Use join() to combine the data frames
result <- join(df1, df2, by = "id")
In this example, the join() function is used to combine two data frames (df1 and df2) based
on a common column (id). The by argument specifies the name of the common column.
The resulting result data frame has three columns (id, name, age) and two rows (one for
each matching value of id in df1 and df2). The values in the name and age columns
correspond to the names and ages of the individuals with the matching id value.
The summarise() function in the plyr package of R is used to aggregate data and calculate
summary statistics by groups. The summarise() function takes several arguments,
including:
Syntax:
Parameters: `data`
object: The data frame to summarize.
Syntax:
Parameters: `…`
object: a list of expressions that calculate summary statistics (e.g. mean(value), sd(value),
etc.)
Example:
Data processing is done by taking data as input from a data frame where the data is organized
into rows and columns. Data frames are mostly used since extracting data is much simpler
and hence easier. But sometimes we need to reshape the format of the data frame from the
one we receive. Hence, in R, we can split, merge and reshape the data frame using various
functions.
The various forms of reshaping data in a data frame are:
Transpose of a Matrix
Joining Rows and Columns
Merging of Data Frames
Melting and Casting
Why R – Data Reshaping is Important?
While doing an analysis or using an analytic function, the resultant data obtained because of
the experiment or study is generally different. The obtained data usually has one or more
columns that correspond or identify a row followed by a number of columns that represent
the measured values. We can say that these columns that identify a row can be the composite
key of a column in a database.
Transpose of a Matrix
We can easily calculate the transpose of a matrix in R language with the help of the t()
function. The t() function takes a matrix or data frame as an input and gives the transpose of
that matrix or data frame as its output.
Syntax:
t(Matrix/ Data frame)
Example:
Output:
[1] "Original Matrix"
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[4,] 10 11 12
# Cbind function
info <- cbind(name, age, address)
print("Combining vectors into data frame using cbind ")
print(info)
# creating new data frame
newd <- [Link](name=c("sounak", "bhabani"),
age=c("28", "87"),
address=c("bangalore", "kolkata"))
# Rbind function
[Link] <- rbind(info, newd)
print("Combining data frames using rbind ")
print([Link])
Output:
[1] "Combining vectors into data frame using cbind "
name age address
[1,] "Shaoni" "24" "puducherry"
[2,] "esha" "53" "kolkata"
[3,] "soumitra" "62" "delhi"
[4,] "soumi" "29" "bangalore"
Output:
name ID
1 arjun 113
2 shaoni 111
3 soumi 112
4 esha 115
5 sounak 114
Melting and Casting
Data reshaping involves many steps in order to obtain desired or required format. One of the
popular methods is melting the data which converts each row into a unique id-variable
combination and then casting it. The two functions used for this process:
melt():
It is used to convert a data frame into a molten data frame.
Syntax: melt(data, …, [Link]=FALSE, [Link]=”value”)
where,
data: data to be melted
… : arguments
[Link]: converts explicit missings into implicit missings
[Link]: storing values
dcast():
It is used to aggregate the molten data frame into a new form.
Syntax: melt(data, formula, [Link])
where,
data: data to be melted
formula: formula that defines how to cast
[Link]: used if there is a data aggregation
Example:
library(reshape2)
Output:
[1] "Melting"
[1] "Casting"
id x1 x2
1 1 4 5.5
2 2 4 2.5
String Manipulations in R
In this section, we will discuss how to manipulate strings in the R programming language
with different types of in-built functions provided by R packages.
The paste () function in R is used to combine two strings or more than two strings together to
form a new string. In other words, the paste() function concatenates vectors after converting
them into characters.
The paste function converts the arguments present in it to character strings and they are
concatenated. If the arguments are vectors, they are concatenated term-by-term to give a
character vector result. Vector arguments are recycled as needed, with zero-length arguments
being recycled to " " only if recycle0 is not true or collapse is not NULL.
Where,
sep is a character string to separate the arguments which are optional. Not
NA_character.
collapse is an optional character string to eliminate the space in between two strings.
Not NA_character. Not to eliminate the space between two words of a single string.
If a value is specified for collapse, the values in the result are then concatenated into a single
string, with the elements being separated by the value of collapse.
Output:
paste("Welcome", "to"," Learn etutorials ", sep = "----") #paste with separator
The sep=”---“ is a character string that separates arguments welcome, to, Learn etutorials
given inside a paste() function.
Output:
> paste("Welcome", "to"," Learn etutorials ", sep = "___") #paste with separator
[1] "Welcome___to___ Learn etutorials "
x <- c("example","of","paste","with","collapse")
print(x)
paste(x)
The vector object x contains several different character strings. When the paste function is
applied over this vector object x, it returns the corresponding result the same as a vector
output. Let us see the output to differentiate vector output(print x) and when paste() function
is applied to vector x (paste(x))..
> print(x)
[1] "example" "of" "paste" "with" "collapse"
> paste(x)
[1] "example" "of" "paste" "with" "collapse"
You can observe that both results are the same. The character strings of vector object x are
not merged with the paste function. So in order to merge elements of a vector object you need
to specify the collapse argument.
In the collapse argument, you need to specify another character string as a separator. Here
collapse = “ “ implies the vector object x elements is going to merge with a blank value.
When the code is run the output is
[Link]() function in R
The nchar() function in the R programming language counts the number of characters
including spaces in a string. This function consists of a character vector as its arguments and
returns a vector whose elements comprising of different sizes of the elements of a string. The
nchar function in R is the fastest and most efficient way to find out if elements of a character
vector are non-empty strings or not.
Where Arguments
Consider an example with a single character object or a variable string [Link] check how
many number characters are contained in string str0 we apply nchar() function over str0.
The function returns a corresponding value in the RStudio console. In our example
applying nchar() in str0 returns a value of 27. Each character is counted including the space
that separates two words within a given single string.
Output:
[1] 27
Now let us consider an example using vector datatype. A vector str1 is created using c()
function with 4 elements welcome", "to", "Learn", "eTutorials" respectively. Applying
nchar() over str1 returns the count of characters in each different word or string inside the
given vector [Link] example the string “welcome” a word/element inside vector return a
value 7 after application of nchar function and so on for remaining elements too.
Output:
> print(str1)
> nchar(str1)
[1] 7 2 5 10
From the output, you can see how many characters correspond to each character string
contained in the given vector.
A vector named vector0 is created with a few elements inside it. Let us see first how the
vector output gets displayed.
print(vector0)
[1] NA "R" "TUTORIAL"
The above strings are displayed in the R console after executing the shortcode. Now let us
find what change does happens to the same code after applying nchar () and together with the
addition of another optional argument 'keepNA'.
> nchar(vector0)
[1] NA 1 8
The NA value is excluded from counting the characters of each string of the given vector, i.e.
vector0. The function counts the rest of the string's characters and returns the value as shown
like “R” with 1 character, “TUTORIAL” with 8 characters, and so on.
When keepNA is set to TRUE, keepNA=TRUE, produces the same result as above.
The NA is not counted, by changing the value from TRUE to FALSE, allows the nchar()
function to count the NA if exists in the given input and returns its corresponding value.
The only difference between nchar() and nzchar() function is that nchar returns numeric
values whereas nzchar() returns a logical value. Consider the nzchar() applied to the same
vector0 created used in our examples, with an optional argument keepNA set to FALSE.
In case vectors contain any empty string represented as “ ” with a non-empty string, they will
return a FALSE value.
[Link]() function in R
The format() function in the R programming language deals with treating all vector elements
as character strings by encoding the vector objects into a common format.
Where Arguments
trim logical; if FALSE, logical, numeric, and complex values are right-justified to a
common width: if TRUE the leading blanks for justification are suppressed.
digits how many significant digits are to be used for numeric and complex x. The
default, NULL, uses getOption("digits"). This is a suggestion: enough decimal places
will be used so that the smallest (in magnitude) number has this many significant
digits, and also to satisfy nsmall. (For the interpretation of complex numbers see
signif.)
nsmall the minimum number of digits to the right of the decimal point in formatting
real/complex numbers in non-scientific formats. Allowed values are 0 <= nsmall <=
20.
#use format() in R
# Place string to the left side
StrFormat1 <- format("Learn eTutorials", width = 25, justify = "l")
# Place string to the center
StrFormat2 <- format("Learn eTutorials", width = 25, justify = "c")
# Place string to the right
StrFormat3 <- format("Learn eTutorials", width = 25, justify = "r")
# Display the different string placement
print(StrFormat1)
print(StrFormat2)
print(StrFormat3)
Output
print(numformat1)
print(numformat2)
print(numformat3)
Output:
[1] "1.45677"
[1] "1.4567700"
justify Takes the values "left", "right", "centre", and "none" to control the padding in
strings.
The below arguments are useful for controlling the printing of numbers,
scientific use TRUE for scientific notation, FALSE for standard notation
[Link]() function in R
In R, the function substr() extracts and returns part of a string from the whole given input
string. For the process of extracting a part from a string, a start and stop integer needs to be
considered. When the substr() is applied to a string, the extraction begins with the starting
integer till it reaches the stop or ending integer. Once it reaches the referred stop integer the
function returns the extracted substring.
Syntax
Where Arguments
Start is an integer, represents the first element from where extraction begins
Stop is an integer, that represents the last element where extraction terminates.
The part of the string after extraction of string str from starting integer 6 and terminating
integer 21 is
Similarly, a vector does perform in the same manner. Consider a vector str0 with a list of
elements or strings like "hello"," Learn"," eTutorials"," learners".
The grep function or grep() in R facilitates the task of identifying or searching a specific
pattern within a string. The grep function returns the number of instances of a searching
pattern if they do find a match similar to the pattern in the string.
The grep() is a pattern matching and replacement function used in R. The grep, grepl,
regexpr, gregexpr, regexec and gregexec search for matches to argument pattern within each
element of a character vector:
sub and gsub perform replacement of the first and all matches respectively.
Where Arguments
x is the input character vector from which the pattern needs to be sought or found.
[Link] is a boolean value set for the case sensitivity option while searching a
pattern.
value is logical to determine whether the output should return the position of the
matching pattern.
fixed is logical.
useBytes is logical to show that in the case of TRUE the pattern is matched byte-by-
byte else character-by-character.
invert = TRUE If TRUE returns indices or values for elements that do not match.
Invert = FALSE If FALSE returns indices or values for elements that do match.
Suppose you need to check a pattern “Learn” in the vector str0. You can use the grep() here.
grep("Learn",str0)
[1] 2 4
The grep() searches pattern & returns a number of instances. For example, the search pattern
“Learn” return the number of instances it occurs at 2, 4.
pattern "Learn"
x str0
[Link] = TRUE Ignores case sensitivity and returns all matching patterns
value = TRUE Returns matching elements itself not indices of matched elements,
where these are patterns that do not match with the given pattern.
Consider what happens when all arguments in the above code are set to FALSE.
The value if FALSE, a vector containing the (integer) indices of the matches determined by
grep() is returned. The pattern “Learn” matches exactly with indices 2 of the str0 vector.
Another simple example is to better understand the argument's value and invert. Returns non-
matching elements as themselves ie as character vectors. The indices are not returned in these
cases.
Try to understand each argument and observe the changes from below given code.
The strsplit() in R is a function to split the elements of a character vector. The strsplit() splits
the given character vector(string) x into substrings based on the split argument provided
within the syntax. The split argument indicates the character vector upon which the string is
split into substrings.
fixed is logical. If TRUE match split exactly, otherwise use regular expressions
useBytes is logical to indicate whether the pattern matching needs to be done byte-by-
byte or character-by-character.
Consider the character variable or string str1 "hello Learn eTutorials learners" applying
strsplit() with the split argument as “ ” returns a list of characters or elements of the string by
splitting the string str1 at the blank spaces as "hello" "Learn" "eTutorials" "learners".
The string is split at the position mentioned by argument split, here split is “Learn
eTutorials”.Let us find its output
Example tolower(x) x= "HELLO" > print(x) [1] "HELLO" > tolower(x) [1] "hello"
toupper(x) > x= "hello" > print(x) [1] "hello" > toupper(x) [1] "HELLO"
Extracting substring
# R program to illustrate
# substring function
# Calling substring() function
substring("Geeks", 2, 3)
substring("Geeks", 1, 4)
substring("GFG", 1, 1)
substring("gfg", 3, 3)
Output :
[1] "ee"
[1] "Geek"
[1] "G"
[1] "g"
String manipulation comprises a series of functions used to extract information from text
variables. In machine learning, these functions are being widely used for doing feature
engineering, i.e., to create new features out of existing string features. In R, we have
packages such as stringr and stringi which are loaded with all string manipulation functions.
R also comprises several base functions for string manipulations. These functions are
designed to complement regular expressions. The practical differences between string
manipulation functions and regular expressions are
For example, suppose you are given a data set comprising the name of the customer as a
variable. In this case, we can use string manipulation functions to extract and create new
features as first name and last name. From the next section onward, we'll learn string
manipulation functions and commands practically. So, make sure you've R installed in your
machine. Also, you should install stringr R package.
In R, a string is any value enclosed in quotes (" "). Yes, you can even have number as strings.
R notifies strings under the class character. Let's see!
R's base paste function is used to combine (or paste) set of strings. In machine learning, it is
quite frequently used in creating / re-structuring variable names. For example, let's say, you
want to use two strings (Var1 and Var2) to create a new string Var3. For neatness, we'll
separate the resultant values using a - (hyphen).
Functions Description
It converts a string to the lower case. Alternatively, you can also use the
tolower()
str_to_lower() function
It converts a string to the upper case. Alternatively, you can also use the
toupper()
str_to_upper() function
setequal() It is used to check if the two vectors have the same string values
To look at the list of all functions contained in the stringr package, go here.
library(stringr)
string <- "Los Angeles, officially the City of Los Angeles and often known by its initials
L.A., is the second-most populous city in the United States (after New York City), the most
populous city in California and the county seat of Los Angeles County. Situated in Southern
California, Los Angeles is known for its Mediterranean climate, ethnic diversity, sprawling
metropolis, and as a major center of the American entertainment industry."
strwrap(string)
#convert to lower
tolower(string)
str_to_lower(string)
#convert to upper
toupper(string)
str_to_upper(string)
#replace strings
chartr("and","for",x = string) #letters a,n,d get replaced by f,o,r
str_replace_all(string = string, pattern = c("City"),replacement = "state") #this is case
sentitive
#abbreviate strings
abbreviate(c("monday","tuesday","wednesday"),minlength = 3)
#split strings
strsplit(x = c("ID-101","ID-102","ID-103","ID-104"),split = "-")
str_split(string = c("ID-101","ID-102","ID-103","ID-104"),pattern = "-",simplify = T)
#find and replace first match
sub(pattern = "L",replacement = "B",x = string,[Link] = T)
The pattern parameter in the functions above also accept regular expressions. These functions
when combined with regular expressions can do highly complex search operations. Now, let's
learn about regular expressions.
Apart from the function listed above, there are several other functions specially designed to
deal with regular expressions (a.k.a regex). Yes, R is equally powerful when it comes to
parsing text data. In regex, there are multiple ways of doing a certain task. Therefore, while
learning, it's essential for you to stick to a particular method to avoid confusion.
For using regular expressions, the available base regex functions are grep(), grepl(),
regexpr(), gregexpr(), regexec(), and regmatches(). Here's a quick preview of these
functions:
Function Description
Grepl returns the Boolean value (True or False) of the matched string
1. Metacharacters
Metacharacters comprises a set of special operators which regex doesn't capture. Yes, regex
work by its own rules. These operators are most common in every line of text you would
come across. These characters include: . \ | ( ) [ ] { } $ * + ?
If any of these characters are available in a string, regex won't detect them unless they are
prefixed with double backslash (\) in R. Let's see how to escape these characters in R.
From a given vector, we want to detect the string "percent%." We'll use the
base grep() function used to detect strings given a pattern. Also. we'll use the gsub() function
to make the replacements. We can do it like this:
dt <- c("percent%","percent")
grep(pattern = "percent\\%",x = dt,value = T)
[1] "percent%"
In fact, if you find a double backslash in a string, you'll need to prefix it with another double
backslash to get detected. Following is an example:
2. Quantifiers
Quantifiers are the shortest to type, but these tiny atoms are immensely powerful. One
position here and there can change the entire output value. Quantifiers are mainly used to
determine the length of the resulting match. Always remember, that quantifiers exercise their
power on items to the immediate left of it. Following is the list of quantifiers commonly used
in detecting patterns in text: It matches everything except a newline.
Quantifier Description
. It matches everything except a newline.
The item to its left is matched exactly n times. The item must have a
{n}
consecutive repetition at place. e.g. Anna
{n,m} The item to its left is matched at least n times but not more than m times.
These quantifiers can be used with metacharacters, sequences, and character classes to
return complex patterns. Combinations of these quantifiers help us match a pattern. The
nature of these quantifiers is better known in two ways:
Greedy Quantifiers : The symbol .* is known as a greedy quantifier. It says that for a
particular pattern to be matched, it will try to match the pattern as many times as its
repetition are available.
Non-Greedy Quantifiers : The symbol .? is known as a non-greedy quantifier. Being
non-greedy, for a particular pattern to be matched, it will stop at the first match.
#greedy
regmatches(number, gregexpr(pattern = "1.*1",text = number))
[1] "1010000000001"
#non greedy
regmatches(number, gregexpr(pattern = "1.?1",text = number))
[1] "101"
3. Sequences
As the name suggests, sequences contain special characters used to describe a pattern in a
given string. Following are the commonly used sequences in R:
Sequences Description
#match a digit
gsub(pattern = "\\d+",replacement = "_",x = string)
regmatches(string,regexpr(pattern = "\\d+",text = string))
#match a non-digit
gsub(pattern = "\\D+",replacement = "_",x = string)
regmatches(string,regexpr(pattern = "\\D+",text = string))
4. Character Classes
Character classes refer to a set of characters enclosed in a square bracket [ ]. These classes
match only the characters enclosed in the bracket. These classes can also be used in
conjunction with quantifiers. The use of the caret (^) symbol in character classes is
interesting. It negates the expression and searches for everything except the specified pattern.
Following are the types of character classes used in regex:
Characters Description
string <- "20 people got killed in the mob attack. 14 got severely injured"
#extract numbers
regmatches(x = string,gregexpr("[0-9]+",text = string))
In R, these classes can be identified as enclosed within a double square bracket ([[ ]]). They
work like character classes. A caret ahead of an expression negates the expression value. I
find these classes more intuitive than the rest, and hence easier to learn. Following are the
posix character classes available in R:
POSIX
Description
Characters
[[:space:]] matches space characters eg. tab, newline, vertical tab, space, etc
string <- c("I sleep 16 hours\n, a day","I sleep 8 hours\n a day.","You sleep how many\t hours
?")
#get digits
unlist(regmatches(string,gregexpr("[[:digit:]]+",text = string)))
#remove punctuations
gsub(pattern = "[[:punct:]]+",replacement = "",x = string)
#remove spaces
gsub(pattern = "[[:blank:]]",replacement = "-",x = string)