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 stringsstr_c("Hello", "World")# [1] "HelloWorld"# With separatorstr_c("Hello", "World", sep = " ")# [1] "Hello World"
Combining vectors
# Element-wise combinationstr_c("a", 1:3)# [1] "a1" "a2" "a3"# Using with paste0-style behaviorstr_c("x", "y", "z")# [1] "xyz"
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
Creating file paths
# Build file paths safelypath_parts <- c("home", "user", "documents", "file.txt")str_c(path_parts, collapse = "/")# [1] "home/user/documents/file.txt"# With base and filenamestr_c("https://", "example.com", "/", "page", ".html")# [1] "https://example.com/page.html"
Handling missing values
# NA propagates by defaultstr_c("a", NA, "b")# [1] NA# Use str_replace_na to convert NA to stringstr_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 defaultstr_c("a", "b")# [1] "ab"# paste uses space by defaultpaste("a", "b")# [1] "a b"# Equivalent to str_cpaste0("a", "b")# [1] "ab"
Common Patterns
Dynamic labels: Create labels for plots and tables