Vassilis Chasiotis
Vassilis Chasiotis

Reputation: 439

A row of a matrix and its reversed in the same matrix in R

Is there any way to find if a row of a matrix is containing in the matrix but in the reversed way?

For example, this happens in the following matrix W:

       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
  [1,]    1    1    1    2    2    2    3    3    3
  [2,]    1    2    3    1    2    3    1    2    3
  [3,]    3    3    3    2    2    2    1    1    1

between the first and the third row.

I have developed the following code, but it works ONLY if a row exists in the matrix in the reversed way:

WW=W[, rev(seq_len(ncol(W)))]

x=match(data.frame(t(W)), data.frame(t(WW)))
A=cbind( c(1:nrow(W)),x )

Z=t(apply(A,1,sort)) 

x=unique(Z[,2])
W=W[-x,]

So, in the previous matrix W, my code does not work, because of NA in the result of the second row of the code.

How can we solve this problem?

Upvotes: 0

Views: 47

Answers (1)

Roland
Roland

Reputation: 132706

"Is there any way to find if a row of a matrix is containing in the matrix but in the reversed way?"

Yes, calculate the distance between rows. If your matrix is not that huge, this is quite efficient:

m <- matrix(c(1, 1, 3, 1, 2, 3, 1, 3, 3, 2, 1, 2, 2, 2, 2, 2, 3, 2, 3, 1, 1, 3, 2, 1, 3, 3, 1), nrow = 3)
res <- as.matrix(dist(rbind(m, 
                            m[, rev(seq_len(ncol(m)))])))
res <- res[nrow(m) + seq_len(nrow(m)), seq_len(nrow(m))]
rownames(res) <- seq_len(nrow(m))

which(!res, arr.ind = TRUE)
#  row col
#3   3   1
#1   1   3

any(!res)
[1] TRUE

Upvotes: 1

Related Questions