model.matrix 来自 r 中的列表

model.matrix from lists in r

我正在尝试将因子列表转换为矩阵,例如:

我的列表:

    [[1]]
    [1] "RA"   "FZFG" "BR"  
    [[2]]
    [1] "RA"
    [[3]]
    [1] ""
    [[4]]
    [1] ""

RA  FZFG  BR
1    1    1
1    0    0
0    0    0
0    0    0

我尝试执行以下操作:

allFactors<-c("RA","FZFG","BR")
mat<-model.matrix(~allFactors,  data =myLists)

但出现错误:

Error in data.frame(c("RA", "FZFG", "BR"), "RA", "", "", "", "", c("RA", : arguments imply differing number of rows: 3, 1, 2, 4, 5, 7, 6, 8, 9

感谢任何帮助。

一个选项是

library(qdapTools)
mtabulate(myLists)[-1]

或使用base R

 table(stack(setNames(myLists, seq_along(myLists)))[2:1])[,-1]

基本 R 选项:

level = unique(unlist(lst))
do.call(rbind, lapply(lst, function(u) table(factor(u, levels=level))))