Retain only rows present in all matrices

若如初见. 提交于 2019-12-10 21:22:44

问题


Suppose one has a list of matrix objects of different lengths, but some row names in common. How could one retain only those rows present in all matrices? I.e., starting with this:

> my.list

$matrix.a
        X1  X2  X3
row.A   59  36  9
row.B   54  29  44
row.C   59  36  9
row.D   54  88  32

$matrix.b
        X1  X2  X3
row.B   47  12  2
row.C   11  36  9
row.D   54  23  99

$matrix.c
        X1  X2  X3
row.A   95  31  77
row.B   63  29  44
row.C   60  43  2

And producing this:

> my.list.subsetted

$matrix.a
        X1  X2  X3
row.B   54  29  44
row.C   59  36  9

$matrix.b
        X1  X2  X3
row.B   47  12  2
row.C   11  36  9

$matrix.c
        X1  X2  X3
row.B   63  29  44
row.C   60  43  2

I suspect that one could use subset() and the %in% operator but I can't seem to find the exact solution.


回答1:


r <- Reduce(intersect, lapply(my.list, rownames))
my.list.subsetted <- lapply(my.list, function(m) m[r, ])


来源:https://stackoverflow.com/questions/20612625/retain-only-rows-present-in-all-matrices

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