从R中的数据框中删除重复的行 [英] Removing duplicate rows from data frame in R
问题描述
我有两列,只想保留非交换行.对于下面的数据,我的输出应包含(1 2)的一种组合.即对于我的查询(1 2)与(2 1)相同.在R中有一种简单的方法吗?已经尝试过转置.并保留上梯形矩阵.但是重新布置数据变得很痛苦.
I have two columns, would like to retain only the non commutative rows.For the data below my output should contain one combination of (1 2). i.e. for my query (1 2) is same as (2 1). Is there a simple way to do it in R. Already tried transposing. and retaining the upper traingular matrix. but it becomes a pain re transposing back the data.
A B prob
1 2 0.1
1 3 0.2
1 4 0.3
2 1 0.3
2 3 0.1
2 4 0.4
我的最终输出应该是:
A B prob
1 2 0.1
1 3 0.2
1 4 0.3
2 3 0.1
2 4 0.4
推荐答案
我们可以使用data.table
.将'data.frame'转换为'data.table'(setDT(df1)
),按pmin(A, B)
和pmax(A,B)
分组,if
行数大于1,我们得到第一行或
We can use data.table
. Convert the 'data.frame' to 'data.table' (setDT(df1)
), grouped by the pmin(A, B)
and pmax(A,B)
, if
the number of rows is greater than 1, we get the first row or else
return the rows.
library(data.table)
setDT(df1)[, if(.N >1) head(.SD, 1) else .SD ,.(A=pmin(A, B), B= pmax(A, B))]
# A B prob
#1: 1 2 0.1
#2: 1 3 0.2
#3: 1 4 0.3
#4: 2 3 0.1
#5: 2 4 0.4
或者我们可以只在pmax
,pmin
输出上使用duplicated
来返回逻辑索引并根据该数据对数据进行子集化.
Or we can just used duplicated
on the pmax
, pmin
output to return a logical index and subset the data based on that.
setDT(df1)[!duplicated(cbind(pmax(A, B), pmin(A, B)))]
# A B prob
#1: 1 2 0.1
#2: 1 3 0.2
#3: 1 4 0.3
#4: 2 3 0.1
#5: 2 4 0.4
这篇关于从R中的数据框中删除重复的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!