0
votes

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.

1
What is your desired output? - dayne
A matrix or list containing vectors of variable lengths, which I join within a loop. - Sahil M
You cannot create jagged matrices in R. You have to give some value to the missing cells. You could create a list of vectors. some.list <- list(b = b, d = d) and then use the list to loop/apply over to do your calculations. What are you doing with the desired matrix/list? - dayne
What I want to do is to feed this matrix/list to box-plot, where each column is operated upon to search for the median, quantiles, etc. - Sahil M

1 Answers

1
votes
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