MikeJewski
MikeJewski

Reputation: 357

Convert matrix of lists (each of length 1) to normal matrix, retaining dimensions

So I seem to have gotten some faulty data, and I would like to extract the data into a more usable state as the calculations will take another day to run. Currently I have a matrix of lists, where each list only contains 1 number. Is it possible to remove each value from the list into a matrix with the same dimensions? Here is a representation of what the output looks like.

filler = 0
for(j in  1:2){
    for(i in 1:10){
        filler[i] <- as.list(i)
    }
    if(j == 1){
        final <- filler
    }else{
        final <- cbind(final,filler)
    }
}
final <- data.matrix(final)

Here is what the output looks like

> final[1,1]
$final
[1] 1

> final
      final filler
[1,] 1     1     
[2,] 2     2     
[3,] 3     3     
[4,] 4     4     
[5,] 5     5     
[6,] 6     6     
[7,] 7     7     
[8,] 8     8     
[9,] 9     9     
[10,] 10    10  

Upvotes: 0

Views: 67

Answers (1)

CL.
CL.

Reputation: 14987

The matrix of lists (each of length 1) final can be converted to a normal matrix using

matrix(unlist(final), nrow = nrow(final), dimnames = dimnames(final))

unlist returns a numeric vector, which is then converted to a new matrix, using the number of rows and dimnames of the original matrix.

Upvotes: 1

Related Questions