[R] Compare two matrices in r
Rui Barradas
ruipbarradas at sapo.pt
Tue Jun 12 13:52:46 CEST 2012
Hello,
There are several notions of "equal". Note that all(mat1 == mat2) alone
doesn't allways do it, it only works if the matrices have equal
dimensions. If they don't, it breaks the code. That's the case of the
first example below.
Try the following.
a <- matrix(1:16, ncol=2)
b <- matrix(1:16, ncol=4, dimnames=list(1:4, letters[1:4]))
d <- matrix(1:16, ncol=4)
a == b # Error in a == b : non-conformable arrays
identical(a, b) # FALSE
all.equal(a, b) # why? different dims and different dimnames
all(d == b) # TRUE but
identical(d, b) # FALSE
all.equal(d, b) # why? different dimnames
# An one line way of solving it.
matequal <- function(x, y)
is.matrix(x) && is.matrix(y) && dim(x) == dim(y) && all(x == y)
matequal(a, b) # FALSE
matequal(d, b) # TRUE
Hope this helps,
Rui Barradas
Em 12-06-2012 08:52, HIMANSHU MITTAL escreveu:
> Dear all,
> I want to compare two matrices . the code must return True only when all
> the elements of the two matices match.
>
> How can this be done in R ?
>
> Regards
>
> [[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.
>
More information about the R-help
mailing list