library(tidyverse)
x <- c("A", "B", "C")
paste0(x, "_1")[1] "A_1" "B_1" "C_1"
May 13, 2021
I often need to add a prefix or suffix to a character vector:
However, if the vector is empty, I do not want bare prefixes or suffixes like this:
I used to write a lot of tedious if statements like this:
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:
If you need to work with an earlier version of R, you can use the sprintf function instead:
[1] "A_1" "B_1" "C_1"
character(0)
The glue function from the glue package also works nicely:
A_1
B_1
C_1
@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}
}