简体   繁体   English

R:传播向量的有效方法

[英]R: Efficient way for spreading vectors

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 eg n=2 并希望通过以下方式进行传播:让我们从例如n = 2开始

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

And now n=4 or any number greater 1 现在n = 4或任何大于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. tidyverse解决方案(用于在管道中使用)对我而言将是最佳解决方案。

(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.) (由于我是R的新手,并且没有正确的搜索条件,因此很难对此任务进行研究。任何帮助都将有所帮助。)

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: 如果对each参数使用rep函数,您将获得所需的内容:

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"

An option is to use rep with argument times = 2 or 4 and then sort the result. 一种选择是使用参数times = 24 rep ,然后sort结果进行sort Another option is to use mapply and then c operator. 另一种选择是使用mapply ,然后使用c运算符。

 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM