Meritshot Tutorials

  1. Home
  2. »
  3. R-Strings

R Tutorial

R-Strings

A string is a sequence of characters. For example, “Meritshot” is a string that includes characters:

M,e,r,i,t,s,h,o,t.

In R, we represent strings using quotation marks (double quotes, ” ” or single quotes, ‘ ‘).

For example,

# string value using single quotes

‘Meritshot’

# string value using double quotes

“Meritshot”

Here, both ‘Meritshot’ and “Meritshot” are Strings. We can use either single quotes or double quotes to represent strings in R.

However, we cannot mismatch them. For example, start the string with a single quote and end it with a double quote, ‘Meritshot” and vice versa, “Meritshot’.

Example: Strings in R

message1 <- ‘Hii ! Students’

print(message1)

message2 <- “Welcome to Meritshot

print(message2)

Output

“Hii ! Students”

“Welcome to Meritshot”

In the above example, we have created string variables named: message1 and message2 with values “Hii ! Students” and “Welcome to Meritshot” respectively.

Here, when we print the string variables, we get the corresponding values.

In R, Strings are represented as sequences of characters and are typically manipulated using various functions from base R and additional packages like stringr. Here are the rules and common practices for string manipulation in R:

Here are the functions available for string manipulation in R:

  • grep()
  • nchar()
  • paste()
  • sprintf()
  • substr()
  • strsplit()
  • regex()
  • gregexpr()

Now, we will understand the R String manipulation functions with their usage.

  1. grep()
    • It is used for pattern matching and replacement. grep, grepl, regexpr, gregexpr and regexec search for matches with argument pattern within each element of a character Here we subsitute the first and other matches with sub and gsub. sub and gsub perform replacement of the first and all matches.

Usage:

grep(“b+”, c(“abc”, “bda”, “cca a”, “abd”), perl=TRUE, value=FALSE)

Output: 1 2 4

  1. nchar()
  • With the help of this function, we can count the characters. This function consists of a character vector as its argument which then returns a vector comprising of different sizes of the elements of nchar is the fastest way to find out if elements of a character vector are non-empty strings or not.

Usage:

str <- “Big Data at MeritShot” print(nchar(str))

This will explicitly print the number of characters in the string str.

  1. paste()

We can concatenate n number of strings using the paste() function.

Usage:

# Company~ MeritShot

paste(“Hadoop”, “Spark”, “and”, “Flink”)