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.
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. ...
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.
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.’
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.
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"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With