Programming
r matrix subset permutation
Updated Sun, 11 Sep 2022 18:43:56 GMT

Select matrix rows that are permutations of a given vector


I have a matrix X:

     one two three four
 [1,]  1   3   2   4
 [2,]  2   0   1   5
 [3,]  3   2   1   4
 [4,]  4   9   11  19
 [5,]  4   3   2   1

I want to get a new matrix Y which only contains rows that are permutations of "1", "2", "3", "4". That is:

     one two three four
 [1,]  1   3   2   4
 [3,]  3   2   1   4
 [5,]  4   3   2   1

What function or command should I use?




Solution

We can try this

> mat[colSums(mapply(`%in%`, list(1:4), asplit(mat, 1))) == ncol(mat), ]
     [,1] [,2] [,3] [,4]
[1,]    1    3    2    4
[2,]    3    2    1    4
[3,]    4    3    2    1