r - How to filter a matrix by the value of another -
i have 2 matrices: m1
, m2
.
m1
:
1 2 3 4 5 1 v11 v12 v13 v14 v15 2 v21 v22 v23 v24 v25 3 v31 v32 v33 v34 v35 4 v41 v42 v43 v44 v45 5 v51 v52 v53 v54 v55
m2
:
x1, x2 1 1 1 2 1 4 2 2 2 3 2 5
i keep m1
if rowname , colname found in m2
, otherwise, write "na" location
e.g. result should be:
m1:
1 2 3 4 5 1 v11 v12 na v14 na 2 na v22 v23 na v25 3 na na na na na 4 na na na na na 5 na na na na na
so far tried use:
m1[!(rownames(m1) %in% m2$x1 & colnames(m1) %in% m1$x2)]<-na
the result not right? suggestions?
in old answer thought op wanted select specific elements m1
, based on m2
. hong ooi's answer works if dimnames of m1
line with row , column indices, , m2
contains integers , not character values. here rough solution if not line up.
m1 <- matrix(c("v11","v21","v12","v22","v13","v23"),nrow=2,ncol=3) dimnames(m1) <- list(c("r2","r1"),c("c1","c2","c3")) m2 <- matrix(c("r1","r1","r2","c1","c3","c3"),nrow=3,ncol=2) > m1 c1 c2 c3 r2 "v11" "v12" "v13" r1 "v21" "v22" "v23" > m2 [,1] [,2] [1,] "r1" "c1" [2,] "r1" "c3" [3,] "r2" "c3" temp <- matrix(true,nrow=nrow(m1),ncol=ncol(m1)) for(i in 1:nrow(m2)){ temp[which(rownames(m1)==m2[i,1]),which(colnames(m1)==m2[i,2])] <- false } m1[temp] <- na > m1 c1 c2 c3 r2 na na "v13" r1 "v21" na "v23"
old answer:
m1 <- matrix(c("v11","v21","v12","v22","v13","v23"),nrow=2,ncol=3) > m1 [,1] [,2] [,3] [1,] "v11" "v12" "v13" [2,] "v21" "v22" "v23" m2 <- matrix(c(1,1,2,1,3,3),nrow=3,ncol=2) > m2 [,1] [,2] [1,] 1 1 [2,] 1 3 [3,] 2 3 keep <- paste(paste0(m2[,1],m2[,2]),collapse="|") m1[!grepl(keep,m1)] <- na > m1 [,1] [,2] [,3] [1,] "v11" na "v13" [2,] na na "v23"
or one-liner:
m1[!grepl(paste(paste0(m2[,1],m2[,2]),collapse="|"),m1)] <- na
Comments
Post a Comment