R中考虑两列的唯一行,无顺序

与我发现的问题不同,我想不按顺序获取两列的唯一性。


我有一个df:


df<-cbind(c("a","b","c","b"),c("b","d","e","a"))

> df

     [,1] [,2]

 [1,] "a"  "b" 

 [2,] "b"  "d" 

 [3,] "c"  "e" 

 [4,] "b"  "a" 

在这种情况下,从ba与ba相同的意义上说,行1和行4是“重复项”。


我知道如何找到列1和2的唯一性,但是在这种方法下,我会发现每一行都是唯一的。


HUH函数
浏览 696回答 3
3回答

www说

有很多方法可以做到这一点,这是一种:unique(t(apply(df, 1, sort)))duplicated(t(apply(df, 1, sort)))一个给出唯一的行,另一个给出掩码。

慕的地8271018

如果只有两列,则还可以使用pmin和pmax,如下所示:library(data.table)unique(as.data.table(df)[, c("V1", "V2") := list(pmin(V1, V2),&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;pmax(V1, V2))], by = c("V1", "V2"))#&nbsp; &nbsp; V1 V2# 1:&nbsp; a&nbsp; b# 2:&nbsp; b&nbsp; d# 3:&nbsp; c&nbsp; e使用“ dplyr”的类似方法可能是:library(dplyr)data.frame(df, stringsAsFactors = FALSE) %>%&nbsp;&nbsp; mutate(key = paste0(pmin(X1, X2), pmax(X1, X2), sep = "")) %>%&nbsp;&nbsp; distinct(key)#&nbsp; &nbsp;X1 X2 key# 1&nbsp; a&nbsp; b&nbsp; ab# 2&nbsp; b&nbsp; d&nbsp; bd# 3&nbsp; c&nbsp; e&nbsp; ce

湖上湖

如果所有元素都是字符串(哎呀,即使不是,也可以强迫它们),那么一个技巧就是将其创建为data.frame并在其中使用一些dplyr技巧。library(dplyr)df <- data.frame(v1 = c("a","b","c","b"), v2 = c("b","d","e","a"))df$key <- apply(df, 1, function(s) paste0(sort(s), collapse=''))head(df)##&nbsp; &nbsp;v1 v2 key## 1&nbsp; a&nbsp; b&nbsp; ab## 2&nbsp; b&nbsp; d&nbsp; bd## 3&nbsp; c&nbsp; e&nbsp; ce## 4&nbsp; b&nbsp; a&nbsp; ab该$key列现在应该告诉您重复。df %>% group_by(key) %>% do(head(., n = 1))## Source: local data frame [3 x 3]## Groups: key##&nbsp; &nbsp;v1 v2 key## 1&nbsp; a&nbsp; b&nbsp; ab## 2&nbsp; b&nbsp; d&nbsp; bd## 3&nbsp; c&nbsp; e&nbsp; ce
打开App,查看更多内容
随时随地看视频慕课网APP