How can I generate mixed sequence like x1,x2,....

Hi Im looking for generating mixed sequence of numbers and chartecter

A <- c("p1", "p2","p3","p4","p5", "p6", "p7","p8","p9","p10", "p11", "p12","p13","p14","p15", "p16", "p17","p18","p19", "p20")

I want to use instead of above line

If you just want to make the mixed sequence once, here is a minimal working example.

paste0("p", 1:3)
#> [1] "p1" "p2" "p3"

If this is something you will need to do often, we can turn this code into a function like this,

mixed_seq <- function(prefix = "", length.out = 1L) {
  paste0(prefix, seq_len(length.out))
}
mixed_seq("p", 3)
#> [1] "p1" "p2" "p3"

If you might need multiple, different mixed sequences, you might try,

mixed_seq <- function(prefix = "", length.out = 1L) {
  as.vector(sapply(prefix, paste0, seq_len(length.out)))
}
mixed_seq("p", 3)
#> [1] "p1" "p2" "p3"
mixed_seq(letters[1:3], 3)
#> [1] "a1" "a2" "a3" "b1" "b2" "b3" "c1" "c2" "c3"

If you want to be able to have a different number for each prefix we can extend it further,

mixed_seq <- function(prefix = "", length.out = 1L) {
  as.vector(unlist(mapply(paste0, prefix, lapply(length.out, seq_len))))
}
mixed_seq("p", 3)
#> [1] "p1" "p2" "p3"
mixed_seq(letters[1:3], 3)
#> [1] "a1" "a2" "a3" "b1" "b2" "b3" "c1" "c2" "c3"
mixed_seq(letters[1:3], 1:3)
#> [1] "a1" "b1" "b2" "c1" "c2" "c3"

Created on 2020-09-06 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.