stringr::str_c()
str_c(..., sep = "", collapse = NULL) The str_c() function from stringr combines multiple strings into one. It is a consistent wrapper around paste0() with helpful defaults and additional features like handling missing values and the collapse argument for joining vector elements.
Syntax
str_c(..., sep = "", collapse = NULL)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
... | character | Required | Two or more character vectors to combine |
sep | character | "" | String to insert between each pair of combined elements |
collapse | character | NULL | If not NULL, collapse a vector into a single string with this separator |
Examples
Basic usage
library(stringr)
# Combine two strings
str_c("Hello", "World")
# [1] "HelloWorld"
# With separator
str_c("Hello", "World", sep = " ")
# [1] "Hello World"
The next example demonstrates combining vectors, building on the pattern established above and showing how the function behaves with a different set of inputs or arguments. Working through these variations step by step reinforces how each parameter affects the output and builds the muscle memory you need to reach for the right function in your own R scripts without having to consult the documentation every time.
Combining vectors
# Element-wise combination
str_c("a", 1:3)
# [1] "a1" "a2" "a3"
# Using with paste0-style behavior
str_c("x", "y", "z")
# [1] "xyz"
The next example demonstrates collapse argument, building on the pattern established above and showing how the function behaves with a different set of inputs or arguments. Working through these variations step by step reinforces how each parameter affects the output and builds the muscle memory you need to reach for the right function in your own R scripts without having to consult the documentation every time.
Collapse argument
# Join vector into single string
str_c(letters[1:5], collapse = ", ")
# [1] "a, b, c, d, e"
# Combine sep and collapse
str_c(c("a", "b", "c"), c("1", "2", "3"), sep = "-", collapse = "|")
# [1] "a-1|b-2|c-3"
The next example demonstrates using in dplyr pipelines, building on the pattern established above and showing how the function behaves with a different set of inputs or arguments. Working through these variations step by step reinforces how each parameter affects the output and builds the muscle memory you need to reach for the right function in your own R scripts without having to consult the documentation every time.
Using in dplyr pipelines
library(dplyr)
df <- data.frame(
first_name = c("John", "Jane", "Bob"),
last_name = c("Doe", "Smith", "Johnson")
)
df %>%
mutate(full_name = str_c(first_name, " ", last_name))
# first_name last_name full_name
# 1 John Doe John Doe
# 2 Jane Smith Jane Smith
# 3 Bob Johnson Bob Johnson
The next example demonstrates creating file paths, building on the pattern established above and showing how the function behaves with a different set of inputs or arguments. Working through these variations step by step reinforces how each parameter affects the output and builds the muscle memory you need to reach for the right function in your own R scripts without having to consult the documentation every time.
Creating file paths
# Build file paths safely
path_parts <- c("home", "user", "documents", "file.txt")
str_c(path_parts, collapse = "/")
# [1] "home/user/documents/file.txt"
# With base and filename
str_c("https://", "example.com", "/", "page", ".html")
# [1] "https://example.com/page.html"
The next example demonstrates handling missing values, building on the pattern established above and showing how the function behaves with a different set of inputs or arguments. Working through these variations step by step reinforces how each parameter affects the output and builds the muscle memory you need to reach for the right function in your own R scripts without having to consult the documentation every time.
Handling missing values
# NA propagates by default
str_c("a", NA, "b")
# [1] NA
# Use str_replace_na to convert NA to string
str_c(str_replace_na(c("a", NA, "b")), collapse = ", ")
# [1] "a, NA, b"
Differences from base R paste()
| Feature | str_c() | paste() |
|---|---|---|
| Default sep | "" (empty) | ” ” (space) |
| NA handling | Returns NA | Returns “NA” as string |
| Recycling | Tidyverse recycling rules | Base R recycling |
| Default | No deparse.labels | Includes deparse.labels |
# str_c uses empty string by default
str_c("a", "b")
# [1] "ab"
# paste uses space by default
paste("a", "b")
# [1] "a b"
# Equivalent to str_c
paste0("a", "b")
# [1] "ab"
The next example demonstrates dynamic plot labels, building on the pattern established above and showing how the function behaves with a different set of inputs or arguments. Working through these variations step by step reinforces how each parameter affects the output and builds the muscle memory you need to reach for the right function in your own R scripts without having to consult the documentation every time.
Common patterns
- Dynamic labels: Create labels for plots and tables
- URL building: Construct URLs from components
- File paths: Build file paths safely
- Text generation: Generate dynamic text messages
Dynamic plot labels
# Create dynamic axis labels
x_var <- "mpg"
y_var <- "disp"
x_label <- str_c("Miles per Gallon (", x_var, ")")
y_label <- str_c("Displacement (", y_var, ")")
x_label
# [1] "Miles per Gallon (mpg)"
y_label
# [1] "Displacement (disp)"
stringr::str_c() in practice
str_c() concatenates strings element-wise, like paste0() but with stricter NA handling. By default, NA in any input position propagates to NA in the output at that position. In contrast, paste0() converts NA to the string "NA". This stricter behavior makes str_c() safer for data cleaning: if a value is missing, you get NA in the output rather than a garbled string like "prefix_NA_suffix".
The sep argument inserts a separator between concatenated strings (default ""), and collapse combines the entire result vector into one string (same as paste()’s collapse). str_c("a", "b", sep="-") gives "a-b". str_c(c("x","y"), collapse=", ") gives "x, y".
str_c() is vectorized and recycles shorter inputs: str_c("item_", 1:5) produces five strings. This matches paste0() recycling behavior. When all inputs are length-1 scalars, str_c() is equivalent to paste0() except for the NA propagation difference.
For complex string templates with multiple variables and format controls, glue::glue() is more readable than str_c(). glue("Hello {name}, you have {n} messages") reads more like a template than the equivalent str_c("Hello ", name, ", you have ", n, " messages"). Use str_c() for simple concatenation and glue() for template strings.
str_c() concatenates strings element-wise. When elements are vectors of different lengths, they recycle to the longest. The sep argument is inserted between each pair of corresponding elements; collapse reduces the result to a single string by joining all elements with that separator. NA inputs produce NA in the output, unlike paste() which coerces NA to the string "NA".
Vectorization behavior
str_c() is vectorized over all its arguments simultaneously. When arguments are vectors of different lengths, recycling applies: shorter vectors are repeated to match the length of the longest. A length-one separator is recycled to concatenate every pair. This recycling is the same as base R’s vector recycling and enables concise combinations of a prefix, a vector of values, and a suffix in one call.
NA propagation in str_c() follows stringr’s general rule: any NA input produces NA output. This differs from paste(), which converts NA to the string “NA”. When your data contains NA values that should produce NA in the concatenated output rather than the string “NA”, use str_c(). When you want NA values to appear as “NA” in the output string, use paste() or convert NAs to the string “NA” before calling str_c().
See also
- stringr::str_detect()
- stringr::str_replace()
- purrr::map()
stringr::str_flatten(x, collapse = ', ')is a cleaner name for the collapsing use case ofstr_c()withcollapse.