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.
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.
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!"
print
or cat
.str <- 'Hello, world!'
print(str)
[1] "Hello, world!"
substr
function.str <- 'Hello'
print(substr(str, 1, 1)) # Accessing using substr function
print(substr(str, 2, 2)) # using substr function
[1] "H" [1] "e"
str <- 'Hello'
str_modified <- sub('H', 'J', str) # Replacing a character
str_modified <- paste0(str_modified, ' World!') # Appending new characters
print(str_modified)
[1] "Jello World!"
paste
or paste0
function.str1 <- 'Hello'
str2 <- ' World!'
str3 <- paste0(str1, str2) # Concatenating strings
print(str3)
[1] "Hello World!"
grepl
function to find a substring.str <- 'Hello, world!'
if (grepl('world', str)) {
print('Substring found')
} else {
print('Substring not found')
}
[1] "Substring found"
nchar
function to get the length of the string.str <- 'Hello, world!'
print(paste('Length of the string:', nchar(str)))
[1] "Length of the string: 13"