2

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

我的清单:

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

但有这个错误:

data.frame 中的错误(c(“RA”,“FZFG”,“BR”),“RA”,“”,“”,“”,“”,c(“RA”,:参数意味着不同的行数: 3, 1, 2, 4, 5, 7, 6, 8, 9

对此的任何帮助表示赞赏。

4

2 回答 2

4

一种选择是

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

或使用base R

 table(stack(setNames(myLists, seq_along(myLists)))[2:1])[,-1]
于 2015-05-24T19:07:43.000 回答
3

基础R选项:

level = unique(unlist(lst))
do.call(rbind, lapply(lst, function(u) table(factor(u, levels=level))))
于 2015-05-24T19:13:40.490 回答