[R] where two matrices differ?
Marc Schwartz
marc_schwartz at me.com
Tue May 31 17:01:02 CEST 2011
Try this:
mat1 <- matrix(c(1,2,1,2), 2, 2)
mat2 <- matrix(c(0,0,1,2), 2, 2)
> mat1
[,1] [,2]
[1,] 1 1
[2,] 2 2
> mat2
[,1] [,2]
[1,] 0 1
[2,] 0 2
> mat1 == mat2
[,1] [,2]
[1,] FALSE TRUE
[2,] FALSE TRUE
# Get the indices of the elements that are not equal
> which(!mat1 == mat2, arr.ind = TRUE)
row col
[1,] 1 1
[2,] 2 1
See ?which
Note that the above comparison presumes that the matrix content is either integer or character, where an exact comparison is possible. If your matrices consist of floats, then you will need to build upon the use of ?all.equal due to:
http://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-doesn_0027t-R-think-these-numbers-are-equal_003f
HTH,
Marc Schwartz
On May 31, 2011, at 9:52 AM, Alaios wrote:
> Thanks alot.
> Unfortunately I can not apply this to much bigger matrices as I can not visually check all the components.
>
> Regards
> Alex
>
> --- On Tue, 5/31/11, Scott Chamberlain <scttchamberlain4 at gmail.com> wrote:
>
> From: Scott Chamberlain <scttchamberlain4 at gmail.com>
> Subject: Re: [R] where two matrices differ?
> To: "Alaios" <alaios at yahoo.com>
> Cc: R-help at r-project.org
> Date: Tuesday, May 31, 2011, 2:56 PM
>
>
> The following returns zeros where elements do match, and NaN's where they don't match
>
> mat1 <- matrix(c(1,2,1,2), 2, 2)mat2 <- matrix(c(0,0,1,2), 2, 2)
> mat1 %% mat2
>
>
>
> ______________________Scott ChamberlainRice University, EEB Dept.
>
>
> On Tuesday, May 31, 2011 at 8:41 AM, Alaios wrote:
>
> Dear all,
> I have a few matrices that are roughly the same (same dimensions).
> How I can find fast which are the elements that differ?
>
> Best Regards
> Alex
>
More information about the R-help
mailing list