This function takes a vector of strings and collapses it into a single string, using specified separators. By default, an error is thrown if the vector is NULL, empty, contains NA values, or empty strings, but these behaviors can be modified.

str_collapse_with(
  strings,
  sep = ", ",
  final_sep = " and ",
  wrap_each_in = NULL,
  error_when_NULL = TRUE,
  error_when_NA = TRUE,
  na_replace = "-"
)

Arguments

strings

A character vector to be collapsed.

sep

A string separator to use between elements, default is ", ".

final_sep

A string separator to use before the last element, default is " and ".

wrap_each_in

A single character or a string of two characters used to wrap each string element. If two characters are given, the first is used as the prefix and the second as the suffix.

error_when_NULL

Logical; if TRUE (default), the function throws an error when strings is NULL or empty.

error_when_NA

Logical; if TRUE (default), the function throws an error when strings contains NA or empty strings.

na_replace

The string to replace NA or empty strings with, if error_when_NA is FALSE.

Value

A single collapsed string. If strings is NULL or empty and error_when_NULL is FALSE, NULL is returned.

Examples

for(i in 1:4){
  print(str_collapse_with(letters[1:i]))
}
#> [1] "a"
#> [1] "a and b"
#> [1] "a, b and c"
#> [1] "a, b, c and d"

str_collapse_with(levels(PlantGrowth$group), final_sep = " und ", wrap_each_in = '`')
#> [1] "`ctrl`, `trt1` und `trt2`"
str_collapse_with(letters[1:5], sep = " & ", final_sep = " as well as ", wrap_each_in = '{}')
#> [1] "{a} & {b} & {c} & {d} as well as {e}"