Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating nested sequences in R

Tags:

r

sequence

paste

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 have searched Stack Overflow for an hour without success. Thank you for any suggestions.

like image 731
Mark Miller Avatar asked Jul 29 '15 09:07

Mark Miller


People also ask

How to create nested list in R with example?

Create Nested List in R (2 Examples) 1 Introducing Exemplifying Data. As you can see based on the previously shown output of the RStudio console, we have created three list objects in R. 2 Example 1: Create List of Lists Using list () Function. ... 3 Example 2: Create List of Lists in for-Loop. ... 4 Video, Further Resources & Summary. ...

How to generate a sequence of numbers in R?

Generating a sequence of numbers is a basic operation in any programming language, and R is no different. Since R language is made for data analysis and complex computations, it provides a seq () function to generate the sequence of numbers. You need to pass the starting point, ending point, and step to create a sequence.

How do you use nested ifelse in R?

This nested ifelse statement tells R to do the following: If the value in the team column is ‘A’ then give the player a rating of ‘great.’ Else, if the value in the team column is ‘B’ then give the player a rating of ‘OK.’ Else, if the value in the team column is ‘C’ then give the player a rating of ‘decent.’

What is the SEQ () method in R?

The seq () is a standard general with a default method to generate the sequence of numbers. The seq () is a built-in R method that generates the regular sequences.


2 Answers

Use paste0, rep with its each argument, and rely on vector recycling:

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"
like image 157
Roland Avatar answered Sep 21 '22 16:09

Roland


Here is an alternative solution that may 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"
like image 26
Lars Lau Raket Avatar answered Sep 20 '22 16:09

Lars Lau Raket