Smartest way for making a sequence of characters in R

Viewed 106

I am going to make the below sequence in R:

A A B B B A A B B B

I have used the below code:

rep(c("A","A","B","B","B"),2)

I got the correct answer as follows:

[1] "A" "A" "B" "B" "B" "A" "A" "B" "B" "B"

But I don't like my code. I would like to see the smartest way for making the above sequence. I don't know if it is possible to make the above sequence using LETTERS[1:2].

Thank you in advance

5 Answers

You can do it without using rep at all:

LETTERS[(0:9 %% 5 > 1) + 1]
 [1] "A" "A" "B" "B" "B" "A" "A" "B" "B" "B"

Here you just replace 9 with however long you want the sequence to be.

You can use rep twice :

rep(rep(LETTERS[1:2], c(2, 3)), 2)
#[1] "A" "A" "B" "B" "B" "A" "A" "B" "B" "B"

A Reduce() version of @RonakShah's answer.

Reduce(rep, list(c(2, 3), 2), LETTERS[1:2])

# [1] "A" "A" "B" "B" "B" "A" "A" "B" "B" "B"

Another variant using rep and LETTERS:

LETTERS[rep(rep(1:2, 2:3), 2)]
# [1] "A" "A" "B" "B" "B" "A" "A" "B" "B" "B"

An option with replicate

unlist(replicate(2, Map(rep, LETTERS[1:2], c(2, 3))))
#[1] "A" "A" "B" "B" "B" "A" "A" "B" "B" "B"
Related