Select equivalent strings [AB & BA]

My problem seems very simple, but I can’t solve it in the morning ...

I have a matrix like this:

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

I want to select rows that have the same information, regardless of the order of the column. For example, line 1 (1; 2) and line2 (2; 1). Then I want to delete them, except for one.

I wrote this function, but it does not 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)

Can anyone give me a hint of this?

+4
source share
1 answer

Like this:

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

Please note that the output lines are sorted, therefore, for example, an “inconsistent” type string c(5, 1)in quality will be displayed in the source data c(1, 5). If instead you want the output lines to be the same as the input, you can do:

mat[!duplicated(t(apply(mat, 1, sort))), ]
+6

All Articles