library(tidyverse)
x <- c("A", "B", "C")
paste0(x, "_1")[1] "A_1" "B_1" "C_1"
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")