[R] Remove rows in a matrix that match rows in another matrix
David Winsemius
dwinsemius at comcast.net
Sun Dec 20 05:59:08 CET 2009
On Dec 19, 2009, at 11:11 PM, Raymond Danner wrote:
> Dear R Community,
>
> The following seems like a simple problem, but I've been stuck on it
> for
> some time, with no luck using matching or subsetting functions. I'm
> trying
> to remove the rows from a large matrix that match rows in another
> large
> matrix. A (small scale) example:
>
> col1<-c("A", "B", "C", "D")
> col2<-c("A", "B", "C", "D")
> m1<-cbind(col1, col2)
> col3<-c("B", "C", "D")
> col4<-c("B", "C", "z")
> m2<-cbind(col3, col4)
>
> Any ideas on how to get the following matrix?
> [,1] [,2]
> [1,] "A" "A"
> [2,] "D" "D"
>
I have an idea but I don't claim it to be the most elegant"
apply(m1, 1, function(x) max( apply(m2, 1, function(y) all.equal(x, y,
check.attributes=FALSE)) ) ) != "TRUE"
[1] TRUE FALSE FALSE TRUE
So....using logical indexing...
m1[apply(m1, 1, function(x) max( # max(c(TRUE,FALSE))==TRUE
apply(m2, 1, function(y) # now cycle through all of
2nd mtx
all.equal(x, y, check.attributes=FALSE)) ) ) !=
"TRUE" , ]
Last logical test "inverts" the result so you get the non-matched rows.
col1 col2
[1,] "A" "A"
[2,] "D" "D"
all.equal is set up to allow ignoring the attributes (col names)
whereas identical did not appear to allow that
> Thanks very much in advance,
> Ray
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list