# [R] Loop elimination question

Prof Brian Ripley ripley at stats.ox.ac.uk
Wed Nov 1 10:21:36 CET 2000

```On Wed, 1 Nov 2000, Murray Jorgensen wrote:

> I want to make a vector built up from several parts. Each part consists of 3
> followed by a variable number of 4s. The number of 4s is given by a vector
> called dim, say
>
> dim <- c(3,1,4,1,5)
>
> From this I want to produce
>
> 3 4 4 4 3 4 3 4 4 4 4 3 4 3 4 4 4 4 4
>
> Now the following code seems to work
>
> type <- numeric(0)
> for (j in seq(along=dim)) {
>       type <- c(type,3,rep(4,dim[j]))}
>
> and I won't really need it to work for very large dim vectors so you could say
> my problem is solved. I am wondering, though, if the loop can be eliminated.

Using rep:

rep(rep(c(3,4), length(dim)), as.vector(t(cbind(1, dim))))

for example.

--
Brian D. Ripley,                  ripley at stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272860 (secr)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._

```