Convert a vector of lists with uneven length to a matrix

自闭症网瘾萝莉.ら 提交于 2019-12-01 06:01:36

问题


I have a vector, well a 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 to 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.


回答1:


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))


来源:https://stackoverflow.com/questions/39247652/convert-a-vector-of-lists-with-uneven-length-to-a-matrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!