Marius - 1 year ago 80
R Question

# r - Convert vector of lists with uneven length to a matrix

I have a resulting data frame with only one column that contains lists of uneven lengths:

``````data = list(
c(349, 364, 393, 356, 357, 394, 334, 394, 343, 365, 349),
c(390, 336, 752, 377),
c(670, 757, 405, 343, 1109, 350, 372),
c(0, 0),
c(),
c(1115, 394, 327, 356, 408, 329, 385, 357, 357))
``````

and i would like to convert it to a matrix, filling the gaps with
`NA`
.
So it should look something like this:

``````349, 364, 393, 356, 357, 394, 334, 394, 343, 365, 349
390, 336, 752, 377, NA,  NA,  NA,  NA,  NA,  NA,  NA
670, 757, 405, 343, 1109,350, 372, NA,  NA,  NA,  NA
0,   0,   NA,  NA,  NA,  NA,  NA,  NA,  NA,  NA,  NA
NA,  NA,  NA,  NA,  NA,  NA,  NA,  NA,  NA,  NA,  NA
1115,394, 327, 356, 408, 329, 385, 357, 357, NA,  NA
``````

eventually even get rid of the rows with only
`NAs`

I have tried
`data = sapply(data[,1], FUN=unlist)`
and then
`data = sapply(data, '[', seq(max(sapply(data, length))))`
but I keep getting a matrix with all the elements unlisted in one column. Please advise.

I guess the 'data' should be a `list` instead of a `vector`, then the code would work

``````t(sapply(data, `length<-`, max(lengths(data))))
``````

NOTE: `lengths` is a faster option (introduced in the recent R versions) that replaces `sapply(data, length)`

### data

``````data = list(
c(349, 364, 393, 356, 357, 394, 334, 394, 343, 365, 349),
c(390, 336, 752, 377),
c(670, 757, 405, 343, 1109, 350, 372),
c(0, 0),
numeric(0),
c(1115, 394, 327, 356, 408, 329, 385, 357, 357))
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download