Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list into a matrix in R

Tags:

r

vector

matrix

I do have a list of vectors, like this:

[[1]]
[1]  1  2  7  9 10 13 14 15 20

[[2]]
[1] 3 4 5 6

[[3]]
[1]  8 11 12

[[4]]
[1] 16 17 18 19

[[5]]
[1] 21 22 23

I want to convert the list to a matrix where the contents of each vector are associated with the list index number in double brackets.

Example:

       [,1] [,2]
 [1,]   1    1
 [2,]   1    2
 [3,]   1    7
 [4,]   1    9
 [5,]   1   10
 [6,]   1   13
 [7,]   1   14
 [8,]   1   15
 [9,]   1   20
[10,]   2    3
[11,]   2    4
[12,]   2    5
[13,]   2    6
[14,]   3    8
[15,]   3   11
[16,]   3   12
[17,]   4   16
[18,]   4   17
[19,]   4   18
[20,]   4   19
[21,]   5   21
[22,]   5   22
[23,]   5   23
like image 808
user2299015 Avatar asked Jun 12 '13 12:06

user2299015


People also ask

Is a list a matrix?

These datastructures are matrices, which are two-dimensional verctors, lists, which are one-dimensional vectors or special objects that can hold items with different types, and arrays, which are vectors with one or more dimensions.

How do I create a matrix from data in R?

To create a matrix in R you need to use the function called matrix(). The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix. Note: By default, matrices are in column-wise order.

How do I convert a list to a vector in R?

Converting a List to Vector in R Language – unlist() Function. unlist() function in R Language is used to convert a list to vector. It simplifies to produce a vector by preserving all components.


1 Answers

You can use unlist to get the values in the list, then use sapply to get the number of values in each element of the list.

# Generate the list
a <- list(1:10, 20:30, 40:45)
# Find the number of elements
num.el <- sapply(a, length)
# Generate the matrix
res <- cbind(unlist(a), rep(1:length(a), num.el))
like image 63
nico Avatar answered Sep 27 '22 21:09

nico