R strings
last modified November 19, 2026
R has no separate string type for a single value: text is stored in a character vector, and a string is simply a character vector of length one. The same functions therefore work on one word and on a column with a million names. This article covers measuring text, changing case, trimming spaces, extracting and replacing substrings, joining and splitting strings, and formatting numbers into labels. Pattern matching with regular expressions has its own article later in the series.
Measuring strings
Two different lengths are easy to confuse. length counts the
elements of the vector, while nchar counts the characters inside
each element and returns one number per string. The next script shows both on
a short vector of words.
words <- c("R", "language", "data")
cat("elements:", length(words), "\n")
print(nchar(words))
cat("total characters:", sum(nchar(words)), "\n")
The vector has three elements, but the words contain one, eight, and four
characters. sum(nchar(words)) adds the character counts and
returns the total length of the text. Both functions are vectorised, so a
single call measures every string without a loop.
$ Rscript string-length.R elements: 3 [1] 1 8 4 total characters: 13
Case and whitespace
toupper and tolower change the case of every
character in every element. trimws removes leading and trailing
whitespace, which is the most common cleanup after reading text from a file
or a web form. Its argument which restricts the removal to one
side.
words <- c(" Alpha ", "BETA", "gamma ")
print(toupper(words))
print(tolower(words))
print(trimws(words))
print(trimws(words, which = "left"))
The first two lines convert the whole vector at once. trimws
then removes the spaces around every word, and the last call removes only the
leading spaces, so the trailing ones survive. Internal spaces are never
touched by trimws; use gsub for those, as the
regular expressions article shows.
$ Rscript case.R [1] " ALPHA " "BETA" "GAMMA " [1] " alpha " "beta" "gamma " [1] "Alpha" "BETA" "gamma" [1] "Alpha " "BETA" "gamma "
Extracting substrings
substr takes a start and a stop position, and both are included
in the result. substring takes only a start and runs to the end
of the string when no stop is given. Positions count characters from one, as
every index in R does.
code <- "2026-11-19" print(substr(code, 1, 4)) print(substr(code, 6, 7)) print(substring(code, 6))
The first call returns the year, the second returns the month, and the third
returns the rest of the date string. An index beyond the end of the string is
not an error: substr simply returns what exists. This makes the
functions safe for fixed-width fields whose last value may be shorter than
expected.
$ Rscript substrings.R [1] "2026" [1] "11" [1] "11-19"
Joining strings
paste combines vectors element by element and separates the parts
with a space by default. paste0 is the same function with an
empty separator. The argument collapse turns a whole vector into a
single string, which is useful for labels and messages.
first <- c("Ada", "Grace")
last <- c("Lovelace", "Hopper")
print(paste(first, last))
print(paste0(first, " ", last))
print(paste(first, collapse = ", "))
The first two lines pair the first names with the last names, and the third
joins the first names into one comma-separated string. Without
collapse the result has one element per input element; with it
the result has length one. The separator can be any string, including an
empty one or a newline.
$ Rscript joining.R [1] "Ada Lovelace" "Grace Hopper" [1] "Ada Lovelace" "Grace Hopper" [1] "Ada, Grace"
Splitting strings
strsplit cuts a string at every occurrence of a separator. It
always returns a list, because one input string can produce a vector of
different lengths, so the result needs one list element per input. The double
bracket selects the parts of the first string.
line <- "red, green , blue"
parts <- strsplit(line, ",")[[1]]
print(parts)
print(trimws(parts))
print(strsplit("a-b-c", "-", fixed = TRUE)[[1]])
The comma-separated line becomes three parts, and trimws removes
the spaces that were left around the parts. The third call uses
fixed = TRUE, which treats the separator as literal text rather
than as a pattern. That argument matters when the separator is a character
such as a dot or a pipe, which has a special meaning in a regular expression.
$ Rscript splitting.R [1] "red" " green " " blue" [1] "red" "green" "blue" [1] "a" "b" "c"
Formatting output
sprintf builds a string from a template. Each conversion starts
with a percent sign: %s inserts a string, %f inserts
a number in fixed notation, and %-6s pads a string to six
characters on the right. The functions format and
formatC offer similar control for whole vectors.
name <- c("Ada", "Alan")
score <- c(90, 66.5)
print(sprintf("%-6s %5.1f", name, score))
print(format(score, nsmall = 2))
print(formatC(score, width = 6, digits = 1, format = "f"))
The template "%-6s %5.1f" prints a left-aligned name in six
columns and a number with one decimal place in five columns. The values are
recycled through the template, so two names and two scores produce two lines.
format(score, nsmall = 2) forces two decimals, and
formatC pads with spaces to a fixed width.
$ Rscript formatting.R [1] "Ada 90.0" "Alan 66.5" [1] "90.00" "66.50" [1] " 90.0" " 66.5"
Replacing characters
substr can appear on the left of an assignment, where it replaces
the characters at the given positions. chartr translates
characters one for one: every character in the old set is replaced by the
character at the same position in the new set. Neither function needs a
regular expression.
word <- "programming"
substr(word, 1, 1) <- "P"
print(word)
print(chartr("aeiou", "AEIOU", word))
The first assignment changes the first letter to an uppercase P. The
chartr call then maps every lowercase vowel to its uppercase
form and leaves the consonants alone. Replacement through substr
requires the replacement to fit the selected range; a longer string would be
truncated to the number of characters selected.
$ Rscript replacing.R [1] "Programming" [1] "PrOgrAmmIng"
A complete example
The next script builds initials from full names. The function splits a name at the space, takes the first character of each part, and joins the two letters. A loop prints one formatted line per name, because the function works on a single string.
full_names <- c("Ada Lovelace", "Grace Hopper", "Alan Turing")
initials <- function(full) {
parts <- strsplit(full, " ")[[1]]
paste0(substr(parts[1], 1, 1), substr(parts[2], 1, 1))
}
for (full in full_names) {
cat(sprintf("%-16s %s\n", full, initials(full)))
}
Ada Lovelace becomes AL, Grace Hopper becomes GH, and Alan Turing becomes AT.
The %-16s conversion aligns the full names in a column, so the
initials start at the same position. The function assumes exactly two parts
per name, which is a reasonable assumption for this input and a reminder to
validate text before splitting it in production code.
$ Rscript report.R Ada Lovelace AL Grace Hopper GH Alan Turing AT
Next steps
The regular expressions article replaces
strsplit and substr with patterns for text whose
shape is not fixed. The dates and times article
parses the date strings that this article only cuts apart, and the
data frames article shows character columns
next to numbers.
Source
An Introduction to R: character vectors
In this article we have measured strings with nchar, changed
their case, and trimmed whitespace. We extracted substrings with
substr, joined them with paste and
paste0, and split them with strsplit. We formatted
numbers with sprintf and formatC, replaced
characters with substr<- and chartr, and built
initials from full names. The series continues with
R regular expressions.
Author
List all R Language tutorials.