Twice as many elements in rep() using the same vector?

82 views Asked by At

I have to solve a question for a class where I have to create a vektor vek1 of length = 60 with twice as many "a" than "b" entries using rep().

My solution is:` x <- c("a", "a", "b") vek1 <- rep(x,each = 1, length.out = 60)

Is there a more beautiful and effective solution to solve the question?

2

There are 2 answers

0
Robert Hacken On BEST ANSWER
rep(rep(c('a', 'b'), c(2, 1)), length.out=60)

This wouldn't probably be my first choice but what I like about this solution is that it uses exactly the information from your question: the two letters, their proportion and the vector length.

0
jblood94 On

Using indexing:

c("a", "b")[1:60%/%1.5%%2+1]

or, since indices are coerced to integers:

letters[40:99/40]

checking the answers:

table(c("a", "b")[1:60%/%1.5%%2+1])
#> 
#>  a  b 
#> 40 20
table(letters[40:99/40])
#> 
#>  a  b 
#> 40 20