[R] construct a vector
Marc Schwartz
marc_schwartz at comcast.net
Wed Nov 26 14:33:24 CET 2008
on 11/26/2008 07:11 AM axionator wrote:
> Hi all,
> I have an unkown number of vectors (>=2) all of the same length. Out
> of these, I want to construct a new one as follows:
> having vectors u,v and w, the resulting vector z should have entries:
> z[1] = u[1], z[2] = v[1], z[3] = w[1]
> z[4] = u[2], z[5] = v[2], z[6] = w[2]
> ...
> i.e. go through the vector u,v,w, take at each time the 1st, 2sd, ...
> elements and store them consecutively in z.
> Is there an efficient way in R to do this?
>
> Thanks in advance
> Armin
Is this what you want?
u <- 1:10
v <- 11:20
w <- 21:30
z <- as.vector(rbind(u, v, w))
> z
[1] 1 11 21 2 12 22 3 13 23 4 14 24 5 15 25 6 16 26 7 17 27 8
[23] 18 28 9 19 29 10 20 30
Essentially, we are creating a matrix from the 3 vectors:
> rbind(u, v, w)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
u 1 2 3 4 5 6 7 8 9 10
v 11 12 13 14 15 16 17 18 19 20
w 21 22 23 24 25 26 27 28 29 30
Then coercing that to a vector, taking advantage of the way in which
matrix elements are stored.
HTH,
Marc Schwartz
More information about the R-help
mailing list