选择等效行 [A-B &B-A] [英] Select equivalent rows [A-B & B-A]

查看:40
本文介绍了选择等效行 [A-B &B-A]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题似乎很简单,但我已经好几个小时没能解决了……

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

我有一个这样的矩阵:

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

我想选择具有相同信息的行,而不考虑列的顺序.例如 row1 (1;2) 和 row2 (2;1).然后,我想删除它们,除了一个.

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 ?

推荐答案

像这样:

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

请注意,输出行已排序,因此例如原始数据中像 c(5, 1) 这样不匹配"的行将显示为 c(1, 5)在输出中.相反,如果您希望输出行与输入行一样,那么您可以这样做:

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))), ]

这篇关于选择等效行 [A-B &amp;B-A]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆