4

我有 2 个矩阵:m1m2.

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    

我只想保留m1rowname 和 colname 在 中找到m2,否则,我想在该位置写“NA”

例如结果应该是:

米1:

    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

到目前为止,我尝试使用:

m1[!(rownames(m1) %in% m2$x1 & colnames(m1) %in% m1$x2)]<-NA

结果不好吗?有什么建议么?

4

2 回答 2

2

我可以想出一个两条线:

m <- m1[NA,]
m[m2] <- m1[m2]
于 2013-08-15T15:10:29.137 回答
2

在我的旧答案中,我认为 OP 想要从 中选择特定元素m1,基于m2. m1如果暗名与行和列索引一致,并且m2包含整数而不是字符值, Hong Ooi 的答案非常有效。如果他们不一定排队,这是一个粗略的解决方案。

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"

老答案:

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"

或作为单行:

m1[!grepl(paste(paste0(m2[,1],m2[,2]),collapse="|"),m1)] <- NA
于 2013-08-15T15:09:34.640 回答