- A+

Suppose I have a list of two matrices, `x`

and `y`

.

` x <- c(3,4,5,5, 3,4,5,6, 5,6,2,1) x <- matrix(x,3,4) y <- c(3,4,5,5, 3,4,5,6, 5,5,2,1) y <- matrix(y,3,4) d <- list(x, y) > x [,1] [,2] [,3] [,4] [1,] 3 5 5 6 [2,] 4 3 6 2 [3,] 5 4 5 1 > y [,1] [,2] [,3] [,4] [1,] 3 5 5 5 [2,] 4 3 6 2 [3,] 5 4 5 1 `

I would like to compare each row of these two matrices using the `identical`

function. Here, the two matrices are the same unless for the last element of the first row.

How could I compare these two matrices, row by row? Any help, please?

My tried is:

`res <- round(apply(array(unlist(d), c(4, 4, 4)), c(1,2), identical),2) `

(from there "I tried the code used here)

But I have got an error:

*Error in FUN(newX[, i], ...) : argument "y" is missing, with no default*

**Please note that the element of the list is arbitrary. That is, sometimes, I have only 2 matrices, however, another time may I have 6 matrices**

**The expected output should be like this**

`output: [,1] [,2] [,3] [,4] [1,] TRUE TRUE TRUE FALSE [2,] TRUE TRUE TRUE TRUE [3,] TRUE TRUE TRUE TRUE `

**1)** This defines `Identical`

to be a function which returns TRUE if all its arguments are identical. It does this by computing the `sd`

of its arguments and comparing that to zero. The second line of code applies this to the corresponding elements of the matrices.

`Identical <- function(...) sd(c(...)) == 0 array(do.call("mapply", c(Identical, d)), dim(d[[1]])) `

giving:

` [,1] [,2] [,3] [,4] [1,] TRUE TRUE TRUE FALSE [2,] TRUE TRUE TRUE TRUE [3,] TRUE TRUE TRUE TRUE `

A few alternate ways to define Identical. These have the advantage that they work with non-numeric matrices as well. The second one uses `identical`

as requested.

`Identical <- function(...) all(c(...)[-1] == ..1) Identical <- function(...) all(sapply(c(...)[-1], identical, ..1)) `

**2)** This alternate method is only one line of code and uses the whole object approach with no explicit use of dimensions or indexes. It unlists `d`

and applies `sd`

over corresponding elements of that using `tapply`

. Finally it compares that to zero.

`tapply(unlist(d), list(sapply(d, row), sapply(d, col)), sd) == 0 `

**2a)** A variation is to define the comparison as a separate function:

`Same <- function(x) sd(x) == 0 tapply(unlist(d), list(sapply(d, row), sapply(d, col)), Same) `

That makes it easier to define alternatives by redefining `Same`

such as the following where the second definition uses `identical`

.

`Same <- function(x) all(x[-1] == x[1]) Same <- function(x) all(sapply(x[-1], identical, x[1])) `