Skip to content
AgileLogics
6 min read

Strings

Prerequisites: Vectors

Text values in R are called strings (type character). Double and single quotes both work; double quotes are the usual style.

Joining and formatting

name <- "Ada"
age <- 36

paste("Hello,", name)
paste0("user_", 1:3)
paste("a", "b", "c", sep = "-")
paste(c("x", "y", "z"), collapse = ", ")
sprintf("%s is %d years old", name, 36L)
sprintf("Price: %.2f", 3.14159)
[1] "Hello, Ada"
[1] "user_1" "user_2" "user_3"
[1] "a-b-c"
[1] "x, y, z"
[1] "Ada is 36 years old"
[1] "Price: 3.14"
  • paste() joins with a space (or sep); paste0() joins with nothing.
  • Both are vectorized: paste0("user_", 1:3) makes three strings.
  • collapse turns a whole vector into one string.
  • sprintf() uses format codes: %s for text, %d for whole numbers, %.2f for decimals with two places.

Common string functions

s <- "  Hello, R World  "
trimws(s)
toupper(s)
nchar("Hello")
substr("Hello", 1, 3)
grepl("World", s)
sub("o", "0", "foo boo")
gsub("o", "0", "foo boo")
strsplit("a,b,c", ",")
startsWith("Hello", "He")
[1] "Hello, R World"
[1] "  HELLO, R WORLD  "
[1] 5
[1] "Hel"
[1] TRUE
[1] "f0o boo"
[1] "f00 b00"
[[1]]
[1] "a" "b" "c"

[1] TRUE
  • sub replaces the first match; gsub replaces all.
  • grepl checks whether a pattern appears. Patterns are regular expressions — the Regex Tester helps you build them.
  • strsplit returns a list (one element per input string), which is why the output shows [[1]]. Use strsplit(x, ",")[[1]] to get the vector for a single string.

The stringr package (Level 2) provides a more consistent set of string functions.

Practice

Given email <- " Ada@Example.COM ", print it trimmed and in lowercase.

Show solution
email <- "  Ada@Example.COM "
tolower(trimws(email))
[1] "ada@example.com"