ywx
ywx

Reputation: 147

Create a new vector formed by a list of vectors

Suppose I have m vectors: a_1 = (a_{11}...a_{1n}) ... a_m = (a_{m1}...a_{mn}) I want a new vector b of length mn such that
b = (a_{11}...a_{m1} a_{12}...a_{m2}...a_{1n}...a_{mn}) I can think of a for loop, for example:

>a<-c(1,1,1);b<-c(2,2,2);c<-c(3,3,3)
>x<-NULL
>for (i in 1:3) {x<-c(x,c(a[i],b[i],c[i]))}
>x
[1] 1 2 3 1 2 3 1 2 3

Is there a better way?

Upvotes: 2

Views: 101

Answers (2)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 59970

Or using mapply...

c( mapply( c , a , b , c )  )
[1] 1 2 3 1 2 3 1 2 3

Upvotes: 4

Hong Ooi
Hong Ooi

Reputation: 57686

c(matrix(c(a, b, c), nrow=length(a), byrow=TRUE))

Upvotes: 2

Related Questions