Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

R transform a list of vectors with differing lengths into a matrix

I have the following list that I would like to transform into the matrix M:

L<-list(c(2L, 29L, 30L), c(1L, 3L, 30L, 31L), c(2L, 31L, 32L), c(5L, 
60L), c(4L, 6L, 60L, 61L), c(5L, 7L, 61L, 62L))

[[1]]
[1]  2 29 30

[[2]]
[1]  1  3 30 31

[[3]]
[1]  2 31 32

[[4]]
[1]  5 60

[[5]]
[1]  4  6 60 61

[[6]]
[1]  5  7 61 62

Matrix M:

2 29 30 NA
1 3 30 31
2 31 32 NA
5 60 NA NA
4 6 60 61
5 7 61 62

I want each list to be a row of the matrix and to fill in any missing values with NA.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Append NA at the end of each list element based on the max length of the list element with length<- and then use rbind with do.call

mx <- max(lengths(L))
do.call(rbind, lapply(L, `length<-`, mx))

-output

    [,1] [,2] [,3] [,4]
[1,]    2   29   30   NA
[2,]    1    3   30   31
[3,]    2   31   32   NA
[4,]    5   60   NA   NA
[5,]    4    6   60   61
[6,]    5    7   61   62
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading