0

I'd like to to convert a list of numeric vectors into a single matrix with different length of columns.

This is the structure of the list, each "Name" is a element of the list :

$ Name 1 : num [1:5] 3 3 4 0 5
$ Name 2 : num [1:4] 3 2 4 0 
$ Name 3 : num [1:7] 3 3 4 0 5 4 4
$ Name 4 : num [1:7] 3 1 4 0 5 5 4

I expect this result:

Name 1 Name 2 Name 3 Name 4
3 3 3 3
3 2 3 1
4 4 4 4
0 0 0 0
5 NA 5 5
NA NA 4 5
NA NA 4 4

How can I build this matrix ? Thank you in advance

benson23
  • 16,369
  • 9
  • 19
  • 38
LZL
  • 91
  • 5

3 Answers3

3

You have to bring all list elements to the same length using length<- and then cbind it to get a matrix.

do.call(cbind, lapply(L, `length<-`, max(lengths(L))))
#     Name 1 Name 2 Name 3 Name 4
#[1,]      3      3      3      3
#[2,]      3      2      3      1
#[3,]      4      4      4      4
#[4,]      0      0      0      0
#[5,]      5     NA      5      5
#[6,]     NA     NA      4      5
#[7,]     NA     NA      4      4

Data

L <- list("Name 1" = c(3, 3, 4, 0, 5),
          "Name 2" = c(3, 2, 4, 0),
          "Name 3" = c(3, 3, 4, 0, 5, 4, 4),
          "Name 4" = c(3, 1, 4, 0, 5, 5, 4))
GKi
  • 37,245
  • 2
  • 26
  • 48
1
    # create a list of numeric vectors
mylist <- list(Name1 = c(3, 3, 4, 0, 5),
               Name2 = c(3, 2, 4, 0),
               Name3 = c(3, 3, 4, 0, 5, 4, 4),
               Name4 = c(3, 1, 4, 0, 5, 5, 4))

# find the maximum length of the vectors in the list
max_len <- max(sapply(mylist, length))

# create an empty matrix of appropriate dimensions
my_matrix <- matrix(NA, nrow = max_len, ncol = length(mylist))


# fill in the matrix with the values from the list
for (i in seq_along(mylist)) {
  vec <- mylist[[i]]
  n <- length(vec)
  my_matrix[1:n, i] <- vec
}

# add column names
colnames(my_matrix) <- names(mylist)

# print the resulting matrix
my_matrix

         Name1 Name2 Name3 Name4
[1,]     3     3     3     3
[2,]     3     2     3     1
[3,]     4     4     4     4
[4,]     0     0     0     0
[5,]     5    NA     5     5
[6,]    NA    NA     4     5
[7,]    NA    NA     4     4
szmple
  • 453
  • 1
  • 8
1
max_len = max(lengths(l))
matrix(
  unlist(
    lapply(l, function(x) {
      c(x, rep(NA, max_len - length(x)))
      })
  ), ncol = length(l)
)
Jon Spring
  • 55,165
  • 4
  • 35
  • 53