Reputation: 335
I want to make the following vector with string elements:
L1 L1 L2 L2 L3 L3 L4 L4 L5 L5 L6 L6 L7 L7 L8 L8 L9 L9 L10 L10
To make this vector, I used the below code:
rep(c("L1","L1","L2","L2","L3","L3","L4","L4"),2)
But I think there is a shorter (easier or simpler) code than my code. Do you have any idea?
Upvotes: 1
Views: 52
Reputation: 886938
An option with rbind
and paste
paste0("L", rbind(1:10, 1:10))
#[1] "L1" "L1" "L2" "L2" "L3" "L3" "L4" "L4" "L5" "L5" "L6" "L6" "L7" "L7" "L8" "L8" "L9" "L9" "L10" "L10"
Or with replicate
paste0("L", t(replicate(2, 1:10)))
Upvotes: 1
Reputation: 520898
You could use:
paste0("L", sort(rep(c(1:10), 2)))
[1] "L1" "L1" "L2" "L2" "L3" "L3" "L4" "L4" "L5" "L5" "L6" "L6"
[13] "L7" "L7" "L8" "L8" "L9" "L9" "L10" "L10"
The idea here is to use rep
to generate the sequence 1:10 twice. Then, we sort ascending to force 1, 1, 2, 2, ..., 10, 10.
Upvotes: 1
Reputation: 8506
Try:
rep(paste0("L", 1:10), each=2)
#> [1] "L1" "L1" "L2" "L2" "L3" "L3" "L4" "L4" "L5" "L5" "L6" "L6"
#> [13] "L7" "L7" "L8" "L8" "L9" "L9" "L10" "L10"
Upvotes: 0
Reputation: 39858
One option could be:
paste0("L", rep(1:10, each = 2))
[1] "L1" "L1" "L2" "L2" "L3" "L3" "L4" "L4" "L5" "L5" "L6" "L6" "L7"
[14] "L7" "L8" "L8" "L9" "L9" "L10" "L10"
Upvotes: 1