Strings in R
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!"
Example 1: Initializing Strings
- Create a string variable and initialize it with a value.
- Print the string variable using
print
orcat
.
R Program
str <- 'Hello, world!'
print(str)
Output
[1] "Hello, world!"
Example 2: Accessing Characters in a String
- Create a string variable and initialize it with a value.
- 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"
Example 3: Modifying Strings
- Create a string variable and initialize it with a value.
- Strings in R are immutable, so you cannot modify individual characters directly but can create new strings based on modifications.
- 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!"
Example 4: String Concatenation
- Create two string variables and initialize them with values.
- Concatenate the strings using the
paste
orpaste0
function. - Print the concatenated string.
R Program
str1 <- 'Hello'
str2 <- ' World!'
str3 <- paste0(str1, str2) # Concatenating strings
print(str3)
Output
[1] "Hello World!"
Example 5: Finding Substrings
- Create a string variable and initialize it with a value.
- Use the
grepl
function to find a substring. - 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"
Example 6: String Length
- Create a string variable and initialize it with a value.
- Use the
nchar
function to get the length of the string. - 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"