R在将列表转换为矩阵时处理NULL值

时间:2014-11-20 19:31:15

标签: r list matrix data-conversion

假设我有如下结构:

data = structure(list(person = structure(list(name = "A, B", 
        gender = "F", dead = NULL), .Names = c("name", 
        "gender", "dead")), person = structure(list(name = "C", 
        gender = "M", dead = "RIP"), .Names = c("name", 
        "gender", "dead"))), .Names = c("person", "person"))

我希望将其转换为矩阵

data = matrix(unlist(data), nrow = length(data), ncol=length(data[[1]]), byrow = TRUE)

在使用matrix时,如何仅使用base函数而不使用plyr rbind.fill时,如何避免回收元素? 结果是:

> data
     [,1]   [,2]  [,3]  
[1,] "A, B" "F"   "C"   
[2,] "M"    "RIP" "A, B"

我希望得到NA"",其值为NULL。例如:

> data
     [,1]   [,2]  [,3]  
[1,] "A, B" "F"   ""   
[2,] "C"    "M"   "RIP" 

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以在stri_list2matrix包中尝试新的stringi功能。

library(stringi)
stri_list2matrix(lapply(data, unlist), byrow=TRUE, fill="")
#      [,1]   [,2] [,3] 
# [1,] "A, B" "F"  ""   
# [2,] "C"    "M"  "RIP"

或者对于NA而不是"",请忽略fill参数

stri_list2matrix(lapply(data, unlist), byrow=TRUE)
#      [,1]   [,2] [,3] 
# [1,] "A, B" "F"  NA   
# [2,] "C"    "M"  "RIP"

或者如果您更喜欢基础R答案,为避免出现问题,您可以先使用length<-使所有向量长度相同。这会将NA附加到所有较短的向量,并使它们与最长向量的长度相同。

len <- max(sapply(data, length)) ## get length of longest vector
t(sapply(unname(data), function(x) `length<-`(unname(unlist(x)), len)))
#      [,1]   [,2] [,3] 
# [1,] "A, B" "F"  NA   
# [2,] "C"    "M"  "RIP"