upabove
upabove

Reputation: 1119

Convert list of vectors into matrix

I have a matrix:

b<-matrix(NA,ncol=100,nrow=10)

and a list of vectors:

load("https://dl.dropboxusercontent.com/u/22681355/a.Rdata")

This list contains 100 vectors. I would like to assign each vector in a list to one column of the matrix. Is this possible to do?

Upvotes: 2

Views: 2673

Answers (5)

Ethan
Ethan

Reputation: 442

matrix(unlist(list(c(1:3), c(4:6), c(7:9))), ncol = 3)

Upvotes: 0

Rcoster
Rcoster

Reputation: 3210

If you call a position bigger than vector's length you got NA in the 'extras positions'. So, a simply mapply does the work:

set.seed(1)
lst <- replicate(10, sample(1:100, sample(5:10, 1))) # Simulating data (Thanks @BrodieG!)

mapply(function(x) x[1:10], lst) # You just need change tha maximium length

Upvotes: 1

BrodieG
BrodieG

Reputation: 52697

One trick is to first "lengthen" the vectors so they are all the same length (in your case 10). Here I start by creating dummy data (only 10 columns so I can show results easily, but this extends to your 100 column case):

set.seed(1)
lst <- replicate(10, sample(1:100, sample(5:10, 1)))   # 10 vectors, length 5-10

Now lengthen, and cbind

lst <- lapply(lst, function(x) { length(x) <- 10; x }) # make all length 10
do.call(cbind, lst)

That's it:

#       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#  [1,]   38   63  100   39   19   65   87   41    9    78
#  [2,]   57    7   38   87   82   78   44   91   87    96
#  [3,]   90   21   77   34   66   55   24   29   34    43
#  [4,]   20   18   91   47   78   52    7   45   82    70
#  [5,]   87   66   21   58   11   76   10   32   98    39
#  [6,]   98   37   62   NA   69    3   31   62   32    31
#  [7,]   NA   73   12   NA   39   45   49   25   45    72
#  [8,]   NA   47   25   NA   NA   69   NA   97   83    NA
#  [9,]   NA   NA   36   NA   NA   64   NA   NA   80    NA
# [10,]   NA   NA   NA   NA   NA   NA   NA   NA   NA    NA

Upvotes: 1

Tyler Rinker
Tyler Rinker

Reputation: 110062

Something like this (don't remember where I got this from):

cbind.fill <- function(nm) {
    nm <- lapply(nm, as.matrix)
    n <- max(sapply(nm, nrow))
    do.call(cbind, lapply(nm, function(x) rbind(x, matrix(, n - nrow(x), ncol(x)))))
}

l <- list(c(1:3), c(4:8), c(7:9))
cbind.fill(l)

## > cbind.fill(l)
##      [,1] [,2] [,3]
## [1,]    1    4    7
## [2,]    2    5    8
## [3,]    3    6    9
## [4,]   NA    7   NA
## [5,]   NA    8   NA

Upvotes: 1

sgibb
sgibb

Reputation: 25736

Have a look at ?do.call and ?cbind, e.g:

## create an example list with 3 vectors
l <- list(c(1:3), c(4:6), c(7:9))

## columnwise binding of all vectors in the list `l`
do.call(cbind, l)

Or you could use a simple for loop:

for (i in seq(along=l)) {
   n <- length(l[[i]])
   b[seq(n), i] <- l[[i]]
}

Upvotes: 5

Related Questions