Reputation: 719
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.
Upvotes: 3
Views: 100
Reputation: 57696
r <- Reduce(intersect, lapply(my.list, rownames))
my.list.subsetted <- lapply(my.list, function(m) m[r, ])
Upvotes: 6