Combine Multiple Strings into a Single String

str_flatten() combines multiple string pieces into a single string. The output is a vector of length 1.

library(stringr)
fruit <- c("mango", "peach", "lemon")str_flatten(fruit)

Output:

[1] "mangopeachlemon"

Use collapse to specify the separator between string pieces. It defaults to be an empty quote (no separator).

# Separate pieces with comma and space.str_flatten(fruit, collapse =  ", ")

Output:

[1] "mango, peach, lemon"

last specifies the separator to connect the last two string pieces.

str_flatten(fruit, collapse =  ", ", last = ", and ")

Output:

[1] "mango, peach, and lemon"

str_flatten_comma() automatically uses a comma as the separator; it has collapse = ", " under the hood.

str_flatten_comma(fruit)

Output:

[1] "mango, peach, lemon"
str_flatten_comma(fruit, last = ", and ")

Output:

[1] "mango, peach, and lemon"