Goal: from a list of vectors of equal length, create a matrix where each vector becomes a row.
Example:
> a <- list() > for (i in 1:10) a[[i]] <- c(i,1:5) > a [[1]] [1] 1 1 2 3 4 5 [[2]] [1] 2 1 2 3 4 5 [[3]] [1] 3 1 2 3 4 5 [[4]] [1] 4 1 2 3 4 5 [[5]] [1] 5 1 2 3 4 5 [[6]] [1] 6 1 2 3 4 5 [[7]] [1] 7 1 2 3 4 5 [[8]] [1] 8 1 2 3 4 5 [[9]] [1] 9 1 2 3 4 5 [[10]] [1] 10 1 2 3 4 5
I want:
[,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 1 2 3 4 5 [2,] 2 1 2 3 4 5 [3,] 3 1 2 3 4 5 [4,] 4 1 2 3 4 5 [5,] 5 1 2 3 4 5 [6,] 6 1 2 3 4 5 [7,] 7 1 2 3 4 5 [8,] 8 1 2 3 4 5 [9,] 9 1 2 3 4 5 [10,] 10 1 2 3 4 5
To convert R List to Matrix, use the matrix() function and pass the unlist(list) as an argument. The unlist() method in R simplifies it to produce a vector that contains all the atomic components which occur in list data.
Convert a Data Frame into a Numeric Matrix in R Programming – data. matrix() Function. data. matrix() function in R Language is used to create a matrix by converting all the values of a Data Frame into numeric mode and then binding them as a matrix.
To convert a vector into matrix, just need to use matrix function. We can also define the number of rows and columns, if required but if the number of values in the vector are not a multiple of the number of rows or columns then R will throw an error as it is not possible to create a matrix for that vector.
One option is to use do.call()
:
> do.call(rbind, a) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 1 2 3 4 5 [2,] 2 1 2 3 4 5 [3,] 3 1 2 3 4 5 [4,] 4 1 2 3 4 5 [5,] 5 1 2 3 4 5 [6,] 6 1 2 3 4 5 [7,] 7 1 2 3 4 5 [8,] 8 1 2 3 4 5 [9,] 9 1 2 3 4 5 [10,] 10 1 2 3 4 5
simplify2array
is a base function that is fairly intuitive. However, since R's default is to fill in data by columns first, you will need to transpose the output. (sapply
uses simplify2array
, as documented in help(sapply)
.)
> t(simplify2array(a)) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 1 2 3 4 5 [2,] 2 1 2 3 4 5 [3,] 3 1 2 3 4 5 [4,] 4 1 2 3 4 5 [5,] 5 1 2 3 4 5 [6,] 6 1 2 3 4 5 [7,] 7 1 2 3 4 5 [8,] 8 1 2 3 4 5 [9,] 9 1 2 3 4 5 [10,] 10 1 2 3 4 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With