0

Is there an efficient way of programming to solve the following task?

Imagine the following vector:

A<-[a,b,c...k]

And would like to spread it the following way: Let‘s start with e.g. n=2

B<-[a,a,b,b,c...,k,k]

And now n=4 or any number greater 1

C<-[a,a,a,a,b,...,k,k,k,k]

To solve it via loops seems kind of easy, but is there any function or vector based operation I missed/could use? A tidyverse solutions (for using it in a pipe) would be the best solution for me.

(It is hard to do research on this task as I am a newbie in R and don‘t the correct terms to search for. Any help would be helpful.)

2 Answers 2

6

Let

A <- letters[1:11]
A
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k"

If you use function rep with argument each, you get what you want:

rep(A, each=2)
 [1] "a" "a" "b" "b" "c" "c" "d" "d" "e" "e" "f" "f" "g" "g" "h" "h" "i" "i" "j"
[20] "j" "k" "k"

rep(A, each=3)
[1] "a" "a" "a" "b" "b" "b" "c" "c" "c" "d" "d" "d" "e" "e" "e" "f" "f" "f" "g"
[20] "g" "g" "h" "h" "h" "i" "i" "i" "j" "j" "j" "k" "k" "k"
1

An option is to use rep with argument times = 2 or 4 and then sort the result. Another option is to use mapply and then c operator.

 c(mapply(rep, 2 ,A)) # OR sort(rep(A, times = 2))
 #[1] "a" "a" "b" "b" "c" "c" "d" "d" "e" "e" "f" "f" "g" "g" "h" "h" "i" "i" "j" "j"
 #[21] "k" "k"

 c(mapply(rep,A, 4))  #OR sort(rep(A, times = 2))
 #[1] "a" "a" "a" "a" "b" "b" "b" "b" "c" "c" "c" "c" "d" "d" "d" "d" "e" "e" "e" "e"
 #[21] "f" "f" "f" "f" "g" "g" "g" "g" "h" "h" "h" "h" "i" "i" "i" "i" "j" "j" "j" "j"
 #[41] "k" "k" "k" "k"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.