不管第1列还是第2列,都为R中的唯一观测值过滤数据帧 [英] Filtering dataframe for unique observations in R, regardless of column 1 or 2
问题描述
考虑以下工作示例。
person_A <- c(1,1,1,2,2,3,3,3,4,4,4,5,6)
person_B <- c(3,4,5,9,1,1,8,7,1,3,7,6,5)
df1 <- data.frame(person_A, person_B)
因此,在每一行中,我们的ID为 person_A
和 person_B
So in each row we have an ID of person_A
and person_B
我要过滤 df1
并删除 person_A
和 person_B
并且仅具有唯一组合作为输出。 但是,我们必须检查已切换的组合(在 person_A
- person_B
和<$之间c $ c> person_B - person_A
)
I want to filter df1
and remove the duplicate combinations of person_A
and person_B
and only have the unique combinations as an output. But, we must check the switched combinations (between person_A
--person_B
and person_B
--person_A
)
换句话说,我要删除以红色阴影的部分
In other words, I want to remove the parts shaded in red
推荐答案
我们可以使用重复的
。我们使用 apply
来按行对排序
元素( MARGIN = 1
),然后转置输出,使用 duplicated
找到重复的元素,作为逻辑 vector
,取反(< c $ c>!),并且仅将 unique
行的子集
We can use duplicated
. We use apply
to sort
the elements by row (MARGIN = 1
), then transpose the output, use duplicated
to find the duplicate elements as logical vector
, negate (!
), and subset only the unique
rows
df1[!duplicated(t(apply(df1, 1, sort))),]
这篇关于不管第1列还是第2列,都为R中的唯一观测值过滤数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!