如何根据R中data.table中具有对称值的两列删除某些行? [英] How can I delete certain rows according to two columns which have symmetricl values in data.table in R?

查看:97
本文介绍了如何根据R中data.table中具有对称值的两列删除某些行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一张表,如下所示:

For example, I have a table as follows:

DT <- data.table(
  A = c(1,1,1,2,2,2,3,3,3), 
  B = c(1,2,3,1,2,3,1,2,3),
  key = "A"
)

我想删除下面的行条件,例如 A == 2和 B == 1,因为已经存在 A == 1和 B == 2的行。

I wand to delete the rows under the conditon such as "A" == 2 and "B" == 1, since there is already the row that "A" == 1 and "B" == 2.

简而言之,我想删除在前几行中已经对称出现的行,我该如何实现?

In short, I want to delete the rows that already appears symmetrically in the previous rows, how can I realize it?

推荐答案

另一种选择:

DT[, g := paste(B, A, sep="_")][A < B, g := paste(A, B, sep="_")][!duplicated(g), !"g"]

   A B
1: 1 1
2: 1 2
3: 1 3
4: 2 2
5: 2 3
6: 3 3

所以...


  1. 将分组变量设为A + B ,

  2. 将子集A<上的订单翻转为B +A。 B或A> B

  3. 对分组变量进行重复

最后一步可以是 unique(DT,by = g)

这篇关于如何根据R中data.table中具有对称值的两列删除某些行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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