01 / 22
Str R

Basic String
Functions in R

Learn to combine, extract, measure, and search text using R's essential string functions: paste, substr, nchar, and grep/grepl.

R Programming

What Are Strings?

In R, a string (also called a character value) is any piece of text wrapped in quotation marks. Strings let you store names, sentences, file paths, labels, and more.

# Creating strings in R name <- "Alice" greeting <- "Hello, world!" class(name) # [1] "character"

Why String Functions Matter

Real-world data is messy. Names arrive in separate columns, dates need reformatting, and you often need to search text for patterns. String functions are your essential toolkit for wrangling text data.

paste / paste0
Combine text together
nchar
Count characters
substr
Extract a portion
grep / grepl
Search for patterns

The Five Core Functions

String Functions paste() Combine with separator paste0() Combine without separator nchar() Count characters substr() Extract substring grep / grepl Search for patterns

paste() and paste0()

paste() joins strings together with a separator (default is a space). paste0() does the same but with no separator at all.

paste("Hello", "World") # [1] "Hello World" paste("2024", "01", "15", sep = "-") # [1] "2024-01-15" paste0("file", ".csv") # [1] "file.csv"

Measuring Length with nchar()

nchar() counts the number of characters in a string, including spaces and punctuation. While length() tells you how many strings are in a vector, nchar() tells you how many characters are in each of those strings.

H e l l o 1 2 3 4 5 nchar("Hello") = 5
nchar("Hello") # [1] 5 nchar("R is fun!") # [1] 9 (space and ! both count)

Extracting with substr()

substr(x, start, stop) extracts a substring from position start to position stop (inclusive on both ends). R uses 1-based indexing.

P r o g r a m m i n g 1 2 3 4 5 6 7 8 9 10 11 start=4, stop=7 → "gram"
substr("Programming", 4, 7) # [1] "gram"

Searching with grep() and grepl()

grep() returns the indices of elements that match a pattern. grepl() returns a logical vector of TRUE/FALSE for each element.

fruits <- c("apple", "banana", "grape", "pineapple") grep("ap", fruits) # [1] 1 3 4 (indices of matches) grepl("ap", fruits) # [1] TRUE FALSE TRUE TRUE
grep()
Returns position numbers (integer vector)
grepl()
Returns TRUE/FALSE (logical vector)

paste() vs paste0(): Key Difference

paste() paste0()
Default separator " " (space) "" (nothing)
sep argument Supported Not used
paste("A","B") "A B" "AB"
collapse argument Supported Supported
Equivalent to paste(..., sep=" ") paste(..., sep="")

grep() vs grepl(): Which to Use?

grep() grepl()
Returns Integer indices Logical (TRUE/FALSE)
Best for Extracting positions Filtering / subsetting
Use with if() Needs \(length() > 0\) Works directly
value=TRUE Returns matching strings Not applicable

Step-by-Step Approach

1
Identify the task: Are you combining, measuring, extracting, or searching?
2
Choose the function: paste/paste0 for combining, nchar for measuring, substr for extracting, grep/grepl for searching.
3
Check your arguments: Does paste need a custom sep? Does substr need the right start/stop positions?
4
Test on a small example: Always run your function on a single string before applying it to an entire vector.
5
Scale up: R's string functions are vectorized: they work on vectors of strings automatically.

Example 1: Building File Names

You have a vector of IDs and need to create file names like "data_001.csv".

ids <- c("001", "002", "003") # Build file names with paste0 files <- paste0("data_", ids, ".csv") files # [1] "data_001.csv" "data_002.csv" "data_003.csv"

Example 2: Extracting Area Codes

You have phone numbers as strings and want to extract the 3-digit area code from the beginning.

5 5 5 - 1 2 3 4 substr(x, 1, 3) = "555" positions 1-3
phone <- "555-1234" area_code <- substr(phone, 1, 3) area_code # [1] "555"

Example 3: Filtering with grepl()

You have a list of email addresses and want to find all the ones from gmail.com.

emails <- c( "alice@gmail.com", "bob@yahoo.com", "carol@gmail.com", "dave@school.edu" ) # Find gmail users is_gmail <- grepl("gmail", emails) is_gmail # [1] TRUE FALSE TRUE FALSE # Subset the vector emails[is_gmail] # [1] "alice@gmail.com" "carol@gmail.com"

The collapse Argument

When you pass a vector to paste(), each element is joined separately. The collapse argument merges all results into a single string.

words <- c("R", "is", "great") # Without collapse: returns 3 separate strings paste(words) # [1] "R" "is" "great" # With collapse: returns 1 combined string paste(words, collapse = " ") # [1] "R is great" paste(words, collapse = "-") # [1] "R-is-great"

Common Mistakes

✕ Confusing paste and paste0
Using paste() when you need no separator gives unwanted spaces: paste("a","b") yields "a b", not "ab".
✕ Off-by-one in substr
Forgetting R is 1-indexed. The first character is position 1, not 0. substr("abc", 0, 2) still returns "ab" but it is misleading.
✕ Using nchar on a vector expecting length()
nchar() counts characters per string. length() counts how many strings are in the vector. They answer different questions.

Summary Reference Table

Function Purpose Example Output
paste() Join with separator paste("a","b") "a b"
paste0() Join without separator paste0("a","b") "ab"
nchar() Count characters nchar("Hello") [1] 5
substr() Extract substring substr("abc",1,2) "ab"
grep() Find match indices grep("a",c("a","b")) [1] 1
grepl() TRUE/FALSE match grepl("a",c("a","b")) [1] TRUE FALSE

Question 1 of 5

What does paste0("data", "_", "2024") return?

Question 2 of 5

What does nchar("R is fun!") return?

Question 3 of 5

What does substr("Banana", 2, 4) return?

Question 4 of 5

Given x <- c("cat", "catch", "dog", "catfish"), what does grepl("cat", x) return?

Question 5 of 5

What is the difference between paste("X", "Y") and paste("X", "Y", sep="")?