Concatenating vectors unless a vector is empty

The paste and paste0 functions have a recycle0 argument that returns an empty vector when any part of the string is empty.
R
Author
Affiliation
Published

May 13, 2021

I often need to add a prefix or suffix to a character vector:

library(tidyverse)
x <- c("A", "B", "C")
paste0(x, "_1")
[1] "A_1" "B_1" "C_1"

However, if the vector is empty, I do not want bare prefixes or suffixes like this:

x <- character(0)
paste0(x, "_1")
[1] "_1"

I used to write a lot of tedious if statements like this:

if (length(x) == 0) {
  y <- character(0)
} else {
  y <- paste0(x, "_1")
}

For R 4.0.1 and later versions, the paste and paste0 functions acquired the recycle0 argument. Setting recycle0 to TRUE returns an empty vector if at least one string is empty:

paste0(x, "_1", recycle0 = TRUE)
character(0)

If you need to work with an earlier version of R, you can use the sprintf function instead:

# Non-empty vector
x <- c("A", "B", "C")
sprintf("%s_1", x)
[1] "A_1" "B_1" "C_1"
# Empty vector
x <- character(0)
sprintf("%s_1", x)
character(0)

The glue function from the glue package also works nicely:

# Non-empty vector
x <- c("A", "B", "C")
glue::glue("{x}_1")
A_1
B_1
C_1
# Empty vector
x <- character(0)
glue::glue("{x}_1")

Citation

BibTeX citation:
@misc{schneider2021,
  author = {Schneider, W. Joel},
  title = {Concatenating Vectors Unless a Vector Is Empty},
  date = {2021-05-13},
  url = {https://wjschne.github.io/posts/concatenating-vectors-unless-a-vector-is-empty},
  langid = {en}
}
For attribution, please cite this work as:
Schneider, W. J. (2021, May 13). Concatenating vectors unless a vector is empty. Schneirographs. https://wjschne.github.io/posts/concatenating-vectors-unless-a-vector-is-empty