Append multiple types of letter to elements in a list

I have a list of string elements:

example <- c("test1", "test2", "test3")

How do I append _A and _B separately to each element in the list? This is the desired output:

example_solution <- c("test1_A", "test1_B", "test2_A", "test2_B", "test3_A", "test3_B")

Thank you!

>Solution :

Base R:

c(outer(example, c("_A", "_B"), FUN = paste0))
# [1] "test1_A" "test2_A" "test3_A" "test1_B" "test2_B" "test3_B"

If order is important, tranpose the inner matrix:

c(t(outer(example, c("_A", "_B"), FUN = paste0)))
# [1] "test1_A" "test1_B" "test2_A" "test2_B" "test3_A" "test3_B"

Leave a Reply