Sahil M
Sahil M

Reputation: 1847

Binding variable length vectors R

I want to bind vectors of different lengths together. I looked up this thread, but it is not clear from this as to how I can make a matrix/list using append or cbind.

As an example, Let's take 2 random vectors of different lengths:

> b<-sample(10,5)
> d<-sample(10,10)

Now operating cbind on them will repeat the smaller vector to whatever possible,

> cbind(b,d)
       b  d
 [1,]  3  7
 [2,]  5  4
 [3,] 10  3
 [4,]  4  2
 [5,]  6  5
 [6,]  3  8
 [7,]  5  6
 [8,] 10 10
 [9,]  4  9
[10,]  6  1

If I try to do append,

> append(b,d)
 [1]  3  5 10  4  6  7  4  3  2  5  8  6 10  9  1

It appends both the vectors into 1. A longer solution will be to save the vector lengths in a different vector, and pick up vectors from this consolidated vector with a loop, using the length vector. But is there a better way to do it? Because I want to put this larger matrix/list into a function, which will become easier if I don't use this length vector based method.

Upvotes: 0

Views: 1201

Answers (1)

dayne
dayne

Reputation: 7784

set.seed(1)
b <- rnorm(10,2,4)
d <- rnorm(50,5,3)
f <- rnorm(100,1,0.5)
example <- list(b=b,d=d,f=f)
for(i in paste("var",1:3)){
  example[[i]] <- rnorm(sample(100,1),mean=sample(5,1),sd=sample(3,1))
}
boxplot(example)

enter image description here

Upvotes: 1

Related Questions