假设我有如下结构:
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"
任何帮助都将不胜感激。
答案 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"