</>
Skip to content
R lessons (14/41)

R — Strings

Basic strings

s <- "Hello, World!"
nchar(s)        # 13
toupper(s)      # HELLO, WORLD!
tolower(s)      # hello, world!

stringr package

library(stringr)

s <- "Hello, World!"

str_length(s)           # 13
str_sub(s, 1, 5)       # Hello
str_replace(s, "World", "R")  # Hello, R!
str_to_upper(s)         # HELLO, WORLD!

Pattern matching

library(stringr)

s <- "The quick brown fox jumps over the lazy dog"

str_detect(s, "fox")        # TRUE
str_extract(s, "\\w+\\s\\w+")  # The quick
str_extract_all(s, "\\w+")  # All words
str_count(s, "the")         # 2 (case-insensitive with regex)

Splitting and joining

library(stringr)

# Split
words <- str_split("apple,banana,cherry", ",")
print(words[[1]])

# Join
fruits <- c("apple", "banana", "cherry")
str_c(fruits, collapse = ", ")

Regex basics

library(stringr)

# Email pattern
emails <- c("alice@example.com", "invalid@", "bob@test.org")
str_detect(emails, "^\\w+@\\w+\\.\\w+$")

# Phone pattern
phones <- c("123-456-7890", "abc-def-ghij")
str_detect(phones, "^\\d{3}-\\d{3}-\\d{4}$")

Mini Practice

Write R code that:

  1. Uses stringr to manipulate strings
  2. Detects patterns with regex
  3. Extracts substrings
  4. Splits and joins strings

Up Next

In the next lesson, you'll learn about Dates — working with dates and times.

Related Topics

Frequently Asked Questions about Strings

What is Strings in R?

Strings is a fundamental concept in R. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Strings?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Strings.

Why is Strings important in R?

Strings is essential for R development. Understanding this concept will help you write better code and solve real-world problems more effectively.