Creating nested sequences in R

I would like to create the following vector , which consists of two nested sequences , plus the letters a and b :

 desired.data <- c('a1b1', 'a1b2', 'a1b3', 'a2b1','a2b2', 'a2b3', 'a3b1', 'a3b2', 'a3b3', 'a4b1','a4b2', 'a4b3', 'a5b1', 'a5b2', 'a5b3') 

I suspect this is a duplicate, but I searched Stack Overflow for an hour without success. Thank you for any suggestions.

+7
r paste sequence
source share
2 answers

Here's an alternative solution that might be more viable if the pattern in the strings is more complex than just two numbers and two characters

 concat <- function(x) paste0('a', x[, 2], 'b', x[, 1]) concat(expand.grid(1:3, 1:5)) #[1] "a1b1" "a1b2" "a1b3" "a2b1" "a2b2" "a2b3" "a3b1" "a3b2" "a3b3" "a4b1" "a4b2" "a4b3" "a5b1" "a5b2" "a5b3" 
+3
source share

Use paste0 , rep with each argument and rely on the vector utility:

 paste0("a", rep(1:5, each = 3), "b", 1:3) #[1] "a1b1" "a1b2" "a1b3" "a2b1" "a2b2" "a2b3" "a3b1" "a3b2" "a3b3" "a4b1" "a4b2" "a4b3" "a5b1" "a5b2" "a5b3" 
+7
source share

All Articles