比较矩阵的行并替换匹配的元素 [英] Comparing rows of matrix and replacing matching elements

查看:61
本文介绍了比较矩阵的行并替换匹配的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想比较两个矩阵.如果第一个矩阵中的行元素与第二个矩阵中的行元素匹配,那么我希望保留第二个矩阵中的行.如果行不匹配,那么我希望这些行为空.抱歉,我最近有一个类似的问题,但我仍然无法解决.

I want to compare two matrices. If row elements in the first matrix matches row elements in the second matrix, then I want the rows in the second matrix to be kept. If the rows do not match, then I want those rows to be to empty. I apologise that I had a quite similar question recently, but I still haven't been able to solve this one.

输入:

> mat1<-cbind(letters[3:8])
> mat1
     [,1]
[1,] "c" 
[2,] "d" 
[3,] "e" 
[4,] "f" 
[5,] "g" 
[6,] "h" 

> mat2<-cbind(letters[1:5],1:5)
> mat2
     [,1] [,2]
[1,] "a"  "1" 
[2,] "b"  "2" 
[3,] "c"  "3" 
[4,] "d"  "4" 
[5,] "e"  "5" 

预期输出:

> mat3
     [,1] [,2]
[1,] "NA" "NA" 
[2,] "NA" "NA" 
[3,] "c"  "3" 
[4,] "d"  "4" 
[5,] "e"  "5" 

我尝试失败了:

> mat3<-mat2[ifelse(mat2[,1] %in% mat1[,1],mat2,""),]

Error in mat2[ifelse(mat2[, 1] %in% mat1[, 1], mat2, ""), ] : 
  no 'dimnames' attribute for array

我已经奋斗了几个小时,因此欢迎提出任何建议.

I have been struggling for hours, so any suggestions are welcomed.

推荐答案

您在正确的轨道上,但是答案比您尝试的要简单一些. mat2 [,1]%in%mat1 [,1] 将匹配项作为逻辑矢量返回,我们可以使用该矢量将不匹配项设置为 NA 索引.

You were on the right track, but the answer is a little simpler than what you were trying. mat2[, 1] %in% mat1[, 1] returns the matches as a logical vector, and we can just set the non-matches to NA using that vector as an index.

mat1<-cbind(letters[3:8])
mat2<-cbind(letters[1:5],1:5)

match <- mat2[,1] %in% mat1 # gives a T/F vector of matches


mat3 <- mat2
mat3[!match,] <- NA

这篇关于比较矩阵的行并替换匹配的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆