Unique rows, considering two columns, in R, withou

2019-01-02 21:19发布

Unlike questions I've found, I want to get the unique of two columns without order.

I have a 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" 

In this case, row 1 and row 4 are "duplicates" in the sense that b-a is the same as b-a.

I know how to find unique of columns 1 and 2 but I would find each row unique under this approach.

4条回答
残风、尘缘若梦
2楼-- · 2019-01-02 21:42

If all of the elements are strings (heck, even if not and you can coerce them), then one trick is to create it as a data.frame and use some of dplyr's tricks on it.

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)
##   v1 v2 key
## 1  a  b  ab
## 2  b  d  bd
## 3  c  e  ce
## 4  b  a  ab

The $key column should now tell you the repeats.

df %>% group_by(key) %>% do(head(., n = 1))
## Source: local data frame [3 x 3]
## Groups: key
##   v1 v2 key
## 1  a  b  ab
## 2  b  d  bd
## 3  c  e  ce
查看更多
宁负流年不负卿
3楼-- · 2019-01-02 21:46

You could use igraph to create a undirected graph and then convert back to a data.frame

unique(get.data.frame(graph.data.frame(df, directed=FALSE),"edges"))
查看更多
不再属于我。
4楼-- · 2019-01-02 21:50

There are lot's of ways to do this, here is one:

unique(t(apply(df, 1, sort)))
duplicated(t(apply(df, 1, sort)))

One gives the unique rows, the other gives the mask.

查看更多
还给你的自由
5楼-- · 2019-01-02 22:04

If it's just two columns, you can also use pmin and pmax, like this:

library(data.table)
unique(as.data.table(df)[, c("V1", "V2") := list(pmin(V1, V2),
                         pmax(V1, V2))], by = c("V1", "V2"))
#    V1 V2
# 1:  a  b
# 2:  b  d
# 3:  c  e

A similar approach using "dplyr" might be:

library(dplyr)
data.frame(df, stringsAsFactors = FALSE) %>% 
  mutate(key = paste0(pmin(X1, X2), pmax(X1, X2), sep = "")) %>% 
  distinct(key)
#   X1 X2 key
# 1  a  b  ab
# 2  b  d  bd
# 3  c  e  ce
查看更多
登录 后发表回答