0

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.

Community
  • 1
  • 1
Sahil M
  • 1,790
  • 1
  • 16
  • 31
  • 1
    What is your desired output? – dayne Aug 21 '13 at 13:22
  • A matrix or list containing vectors of variable lengths, which I join within a loop. – Sahil M Aug 21 '13 at 13:24
  • 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 Aug 21 '13 at 13:26
  • 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 Aug 21 '13 at 13:28

1 Answers1

1
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

dayne
  • 7,504
  • 6
  • 38
  • 56
  • I have to append to this list over a loop, will append(example, x) work in a loop? It is currently making each element of x as an a single element of the list. – Sahil M Aug 21 '13 at 13:40
  • @SahilM See the edit. You can add elements to a list with a loop. You should probably spend some time reading about lists in r. – dayne Aug 21 '13 at 13:47