Strings in R

R BasicsStringsFree Lesson

Advertisement

Introduction

R provides powerful capabilities for working with character strings. The stringr package makes string manipulation intuitive.

Creating Strings

# Using quotes
str1 <- "Hello"
str2 <- 'World'

# Multiple strings
fruits <- c("apple", "banana", "orange")

# Escape characters
quote <- "She said \"Hello\""

String Functions (base R)

str <- "Hello World"

nchar(str)           # Length: 11
toupper(str)         # "HELLO WORLD"
tolower(str)         # "hello world"
substr(str, 1, 5)    # "Hello"
paste("Hello", "World")  # "Hello World"
paste0("Hello", "World") # "HelloWorld"
strsplit(str, " ")   # Split into list

Stringr Package

library(stringr)

str <- "Hello World"

str_length(str)       # Length
str_to_upper(str)     # Uppercase
str_to_lower(str)     # Lowercase
str_sub(str, 1, 5)   # Substring
str_detect(str, "Hello")  # Detect pattern
str_replace(str, "World", "R")  # Replace
str_extract(str, "[A-Z]+")  # Extract pattern

String Formatting

name <- "Alice"
age <- 30

# sprintf
sprintf("Name: %s, Age: %d", name, age)

# paste with collapse
items <- c("a", "b", "c")
paste(items, collapse = ", ")

Pattern Matching

library(stringr)

text <- "The quick brown fox"

str_detect(text, "quick")     # TRUE
str_starts(text, "The")       # TRUE
str_ends(text, "fox")         # TRUE
str_count(text, "o")          # Count occurrences

Summary

String manipulation is essential for text processing. Use stringr for consistent and readable code.

Advertisement

Need Expert R Programming Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement