R Strings


R Strings

In this tutorial, we will learn about strings in R. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.


What is a String

A string in R is a sequence of characters. Strings in R can be created using double quotes or single quotes. Strings are used for storing and handling text data.


Creating Strings

Strings can be created in R using single or double quotes:

str <- 'Hello, world!'

Strings can also be created using double quotes:

str2 <- "Hello,\nworld!"


Initializing Strings

  1. Create a string variable and initialize it with a value.
  2. Print the string variable using print or cat.

R Program

str <- 'Hello, world!'
print(str)

Output

[1] "Hello, world!"


Accessing Characters in a String

  1. Create a string variable and initialize it with a value.
  2. Access and print individual characters using the substr function.

R Program

str <- 'Hello'
print(substr(str, 1, 1)) # Accessing using substr function
print(substr(str, 2, 2)) # using substr function

Output

[1] "H"
[1] "e"


Modifying Strings

  1. Create a string variable and initialize it with a value.
  2. Strings in R are immutable, so you cannot modify individual characters directly but can create new strings based on modifications.
  3. Print the modified string.

R Program

str <- 'Hello'
str_modified <- sub('H', 'J', str) # Replacing a character
str_modified <- paste0(str_modified, ' World!') # Appending new characters
print(str_modified)

Output

[1] "Jello World!"


String Concatenation

  1. Create two string variables and initialize them with values.
  2. Concatenate the strings using the paste or paste0 function.
  3. Print the concatenated string.

R Program

str1 <- 'Hello'
str2 <- ' World!'
str3 <- paste0(str1, str2) # Concatenating strings
print(str3)

Output

[1] "Hello World!"


Finding Substrings

  1. Create a string variable and initialize it with a value.
  2. Use the grepl function to find a substring.
  3. Print the existence of the substring.

R Program

str <- 'Hello, world!'
if (grepl('world', str)) {
  print('Substring found')
} else {
  print('Substring not found')
}

Output

[1] "Substring found"


String Length

  1. Create a string variable and initialize it with a value.
  2. Use the nchar function to get the length of the string.
  3. Print the length of the string.

R Program

str <- 'Hello, world!'
print(paste('Length of the string:', nchar(str)))

Output

[1] "Length of the string: 13"