Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select equivalent rows [A-B & B-A] [duplicate]

Tags:

r

My problem seems to be very simple but I'm not able to solve it since hours…

I have a matrix such this one:

      [,1] [,2]
[1,]    1    2
[2,]    2    1
[3,]    2    1
[4,]    3    4

I want to select the rows which have the same information, without regard to the order of the column. For instance row1 (1;2) and row2 (2;1). Then, i want to delete them, except one.

I have written this function, but it doesn't work…

f<-function(x){
     i<-1
     repeat
     {
     a<-c()
     a<-c(which(x[i,1]==x[,2] & x[i,2]==x[,1]))
          if(!is.null(a)) {x<-x[-c(a),]}
          if(i>=nrow(x)) {break} else {i<-i+1}
     }
     x
} 
f(data)

Somebody could give me a hint for this ?

like image 662
RechercheR Avatar asked Oct 29 '13 01:10

RechercheR


1 Answers

Like this:

unique(t(apply(mat, 1, sort)))

Note that output rows are sorted, so for example an "unmatched" row like c(5, 1) in the original data will appear as c(1, 5) in the output. If instead you want the output rows to be as they are in the input, then you can do:

mat[!duplicated(t(apply(mat, 1, sort))), ]
like image 143
flodel Avatar answered Sep 28 '22 00:09

flodel