Search code examples
rloopsmatrixvectorcbind

Is there a trick to looping with cbind?


I have 87 vectors of length 4096. For example,

> head(d[[1]]$x)
[1] 1.676094 1.676323 1.676551 1.676780 1.677008 1.677237

I would like to concatenate these vectors into a matrix with each vector occupying a column. Because cbinding them individually works fine

Ds <- cbind(d[[1]]$x,d[[2]]$x,d[[3]]$x)

I thought this would work too

matrix() -> Ds
for(i in 1:87){
    cbind(d[[i]]$x) -> Ds[[i]]
}

but I get the error

Error in Ds[[i]] <- cbind(d[[i]]$x) : 
  more elements supplied than there are to replace

Is there something specific about cbind that doesn't allow for looping or am I missing something? Any advice is appreciated.

Thanks.


Solution

  • cbind needs two or more arguments. Can you try:

    Ds<-c() 
    for(i in 1:87){
         Ds<-cbind(Ds,d[[i]]$x) 
    }