model.matrix from lists in r

落花浮王杯 提交于 2019-12-08 00:12:14

问题


I am trying to convert list of factors to matrix for example:

myLists:

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

to

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

I tried to do the following:

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

but have ths error:

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

Any help on this is appreciated.


回答1:


One option is

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

Or using base R

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



回答2:


Base R option:

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


来源:https://stackoverflow.com/questions/30427235/model-matrix-from-lists-in-r

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