0

I am trying to get the intersection of two lists containing matrices in R, however I want to include very similar matrices too. For example:

a = 
    0.012  0.013
    0.055  0.100

b = 
    0.013  0.013
    0.055  0.100

c = 
    0.013  0.014
    0.056  0.101

If a is in list one, b and c are in list two, they should all be included in the output intersect-list. I know that all.equal is a great function to return true in these cases, and intersect function returns a list of exactly same matrices found, I just don't know how to combine them to get the result I want. Thank you for looking into this.

Edit: here is a code that generates example lists of matrices: https://pastebin.com/2yK4sj8G

ayshelina
  • 137
  • 1
  • 10
  • Hey ayshelina, could you provide the reproducible example of your data, especially lists with matrices? Otherwise, it's difficult to help. https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Alex Knorre Oct 21 '17 at 18:13
  • Example added thanks. – ayshelina Oct 21 '17 at 20:50

1 Answers1

0

Here is one possible way to compare nearly similar matrices.

a = matrix(c(0.012, 0.013, 
             0.055, 0.100),2,2,byrow = TRUE)

b = matrix(c(0.013, 0.013, 
             0.055, 0.100),2,2,byrow = TRUE)

c = matrix(c(0.012, 0.014, 
             0.055, 0.100),2,2,byrow = TRUE)

matrix_compare = function(x,y,threshold) {
  return( all( abs(x-y) <= threshold ) )
}

We compare that the absolute difference between all individual matrix element values are below a threshold:

> matrix_compare(a,b,threshold=0.001)
[1] TRUE

However, beware of rounding errors, when comparing the difference!

> matrix_compare(a,c,threshold=0.001)
[1] FALSE

Therefore, one should introduce also a rounding error threshold (1e-16) and add it to the desired comparison threshold (0.001):

> matrix_compare(a,c,threshold=0.001+1e-16)
[1] TRUE
Heikki
  • 2,214
  • 19
  • 34
  • thank you, this is a part of the solution but I am having trouble applying this function in a way that it produces a new list of all similar matrices from two input lists of matrices. – ayshelina Oct 22 '17 at 08:44
  • Will it be (i) one matrix vs. a list of matrices, or, (ii) a list of matrices vs. another list of matrices? – Heikki Oct 22 '17 at 18:33
  • (ii) a list of matrices vs. another list of matrices – ayshelina Oct 23 '17 at 11:08