Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 39 ยท Strings, Dates and Regular Expressions

R Strings: Create, Combine, Format and Slice Text

Learn how to work with text in R: creating strings, paste and paste0, nchar, substr, strsplit, case changes, sprintf and format, raw strings and common mistakes.

Almost every real data set contains text: names, addresses, product codes, comments. In R, text lives in character vectors. A single string such as "hello" is just a character vector of length one, so every function in this lesson works on a whole vector of strings at once, without a loop.

This lesson covers the base R tools: building strings, measuring them, cutting them apart, changing case and formatting numbers as text. The next lessons add regular expressions and the tidyverse helpers in stringr and lubridate.

R does not run on this site, so the R code in this chapter is read-only. Output lines are shown only where we are certain of them. Where it helps, a Python block does the same job so that you can run it and compare.

Creating strings

Use double or single quotes; they mean the same thing. Prefer double quotes and use single quotes only to avoid escaping.

R
a <- "R is fun"
b <- 'She said "hi"'
c <- "tab\there"        # \t is a tab, \n a new line, \\ a backslash

print(c)                # shows the escape:  "tab\there"
cat(c, "\n")            # prints the real tab: tab    here

print() shows the string as R stores it (with quotes and escapes); cat() writes the characters themselves. writeLines() prints each element on its own line, which is handy for messages.

Since R 4.0 you can write a raw string with r"(...)". Backslashes inside are not escapes, which is a relief for Windows paths and regular expressions:

R
path <- r"(C:\temp\data.csv)"
nchar(path)             # 16

Measuring: nchar

nchar() returns the number of characters, and it is vectorized:

R
nchar("R is fun")                  # 8
nchar(c("apple", "kiwi", "fig"))   # 5 4 3

Spaces and punctuation count. Use nchar(x, type = "bytes") when you need the byte size, for example for text with accents or emoji.

Combining: paste and paste0

paste() joins its arguments with a separator (a space by default). paste0() joins with no separator.

R
paste("a", "b")                    # "a b"
paste("x", 1:3, sep = "_")         # "x_1" "x_2" "x_3"
paste0("id", 1:3)                  # "id1" "id2" "id3"
paste(c("a", "b", "c"), collapse = " + ")   # "a + b + c"

The difference between sep and collapse trips up many beginners. sep goes between the arguments of one call and the result is still a vector. collapse glues the elements of the result into a single string. Both can be used together:

R
paste("item", 1:3, sep = "-", collapse = ", ")   # "item-1, item-2, item-3"

Shorter vectors are recycled, so paste0("Q", 1:4, "-2026") produces four strings from a single suffix.

Slicing: substr, substring and strsplit

substr(x, start, stop) extracts positions (1-based, both ends included). substring() is the vectorized-in-positions cousin.

R
s <- "R is fun"
substr(s, 6, 8)                    # "fun"
substring("abcdef", 1:3, 3:5)      # "abc" "bcd" "cde"

You can assign into substr() to overwrite characters: substr(s, 1, 1) <- "Z" turns "R is fun" into "Z is fun".

strsplit(x, split) breaks each string into pieces and returns a list, one element per input string, because each input can produce a different number of pieces:

R
strsplit("a,b,c", ",")
# [[1]]
# [1] "a" "b" "c"

strsplit(c("1-2", "3-4-5"), "-")   # list of two character vectors
unlist(strsplit("a,b,c", ","))     # "a" "b" "c"

The split argument is a regular expression by default, so strsplit("a.b", ".") does not do what you expect (a dot matches any character). Use fixed = TRUE for a literal split: strsplit("a.b", ".", fixed = TRUE). Splitting on an empty string (or NULL) gives single characters, which gives us the classic string reversal:

R
paste(rev(strsplit("hello", NULL)[[1]]), collapse = "")   # "olleh"

Changing case and cleaning

R
toupper("hello")           # "HELLO"
tolower("HeLLo")           # "hello"
trimws("  hi  ")           # "hi"
trimws("  hi  ", which = "left")   # "hi  "
chartr("abc", "xyz", "aabbcc")     # "xxyyzz"  (letter-by-letter swap)
startsWith("report.csv", "rep")    # TRUE
endsWith("report.csv", ".csv")     # TRUE

R has no built-in "title case" for one word, but you can build it from the pieces you already know:

R
w <- "hello"
paste0(toupper(substring(w, 1, 1)), substring(w, 2))   # "Hello"

trimws() is the first thing to apply to text typed by humans: stray spaces make "yes " differ from "yes" and silently break comparisons and joins.

Formatting numbers as text

sprintf() follows the C printf conventions and is vectorized over all its arguments:

R
sprintf("%d items", 3L)                  # "3 items"
sprintf("%5.1f", 3.14159)                # "  3.1"
sprintf("%03d", 7L)                      # "007"
sprintf("%5s|%-5s|", "ab", "cd")         # "   ab|cd   |"
sprintf("%d%%", 50L)                     # "50%"
sprintf("Name: %s, Age: %d", c("Ann", "Bob"), c(30L, 25L))
# "Name: Ann, Age: 30" "Name: Bob, Age: 25"

%s is a string, %d an integer, %f a fixed-point number, %e scientific, %% a literal percent sign. A number between % and the letter sets the width; - left-aligns; 0 pads with zeros. Be aware that %.0f rounds half to even (the C behavior): sprintf("%.0f", 2.5) is "2" while sprintf("%.0f", 3.5) is "4".

format() and formatC() are the other two tools:

R
format(1234567.891, big.mark = ",")      # "1,234,568"   (7 significant digits)
format(2, nsmall = 2)                    # "2.00"
format(c(1, 10, 100))                    # "  1" " 10" "100"  (common width)
formatC(42, width = 8, flag = "0")       # "00000042"
formatC(3.14159, digits = 3, format = "f")   # "3.142"

Rule of thumb: use sprintf() for messages and reports, format() for printing numbers nicely, formatC() when you want exact control of width and digits.

Character codes and conversions

R
utf8ToInt("A")              # 65
intToUtf8(c(72, 105))       # "Hi"
strtoi("ff", base = 16L)    # 255
as.character(42)            # "42"
as.numeric("3.5")           # 3.5
as.numeric("abc")           # NA, with a warning

Built-in constants help: letters, LETTERS and month.name are ready-made character vectors.

The same ideas in Python

The functions have different names, but the concepts transfer directly. This block is a comparison you can run; it is Python, not R.

Python Python comparison: R string functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Forgetting that strsplit() returns a list. Use [[1]] or unlist().
  • Using paste() when you want no space. Use paste0().
  • Treating ., | or ( in strsplit() or gsub() as plain text. They are regex characters; add fixed = TRUE.
  • Comparing strings that differ only by case or surrounding spaces. Normalize with tolower() and trimws() first.
  • Expecting nchar(NA) to be NA: for a logical NA it is 2; for NA_character_ it is NA.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does paste(c('a', 'b', 'c'), collapse = '-') return?

    collapse joins the elements of the result into one string using the given separator.
  2. 2. Why does strsplit() return a list?

    The input is a vector of strings, and every string may split into a different number of parts, so a list is the natural container.
  3. 3. Which call returns "007"?

    %03d pads the integer with zeros to a width of 3. %3d pads with spaces, and paste0('00', 7L) gives "007" only by luck for one-digit numbers.
  4. 4. What is the safest way to split "a.b.c" on literal dots?

    With fixed = TRUE the split is a literal string, so a dot is just a dot. Without it, a dot is a regular expression that matches any character.

Summary

  • Strings are character vectors; nearly every function is vectorized.
  • paste() uses sep between arguments and collapse to join the result; paste0() has no separator.
  • nchar(), substr(), substring() and strsplit() measure and cut text; strsplit() returns a list.
  • toupper(), tolower() and trimws() clean text; sprintf(), format() and formatC() turn numbers into text.
  • Raw strings r"(...)" avoid backslash trouble.

Next: Regular Expressions in R