r - Search a matrix for rows with given values in any order -


i have matrix , vector values:

mat<-matrix(c(1,1,6,               3,5,2,               1,6,5,               2,2,7,               8,6,1),nrow=5,ncol=3,byrow=t)  vec<-c(1,6) 

this small subset of n n matrix , 1 n vector. there way can subset rows values in vec?

the straight forward way of doing know of use subset function:

subset(mat,vec[,1] == 1 & vec[,2] == 6) #etc etc 

the problem subset have specify in advance column , specific combination for. problem facing structured in way such want find rows containing numbers in "vec" in possible way. in above example, want return matrix of:

1,1,6 1,6,5 8,6,1 

any ideas?

you can do

apply(mat, 1, function(x) all(vec %in% x)) #  [1]  true false  true false  true 

but may give unexpected results if vec contains repeated values:

vec <- c(1, 1) apply(mat, 1, function(x) all(vec %in% x)) # [1]  true false  true false  true 

so have use more complicated using table account repetitions:

vec <- c(1, 1) is.sub.table <- function(table1, table2) {   all(names(table1) %in% names(table2)) &&   all(table1 <= table2[names(table1)]) } apply(mat, 1, function(x)is.sub.table(table(vec), table(x))) # [1]  true false false false false 

however, if vector length equal number of columns in matrix seem indicate not case in example, should do:

vec <- c(1, 6, 1) apply(mat, 1, function(x) all(sort(vec) == sort(x))) # [1]  true false false false false 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -