Comparing rows of matrix and replacing matching elements

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.

INPUT:

> 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" 

Expected OUTPUT:

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

I have unsuccessfully attempted this:

> 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.

Upvotes: 0

Views: 131

Answers (1)

Lief Esbenshade
Lief Esbenshade

Reputation: 833

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

Upvotes: 1

Related Questions