我有一个数据框,其中包含两列中的重复值。
dat<-data.frame(V1 = c("home","cat","fire","sofa","kitchen","sofa"),
V2 = c("cat","home","water","TV","knife","TV"), V3 = c('date1','date1','date2','date3','date4','date3'))
V1 V2 V3
1 home cat date1
2 cat home date1
3 fire water date2
4 sofa TV date3
5 kitchen knife date4
6 sofa TV date1
我想从此数据帧中获得唯一的对,而忽略该对在两列之间的显示顺序。
这就是我想要获得的结果:
V1 V2 V3
1 home cat date1
2 fire water date2
3 sofa TV date3
4 kitchen knife date4
答案 0 :(得分:1)
dat[!duplicated(t(apply(dat, 1, sort))),]
使用apply
和sort
将遍历每一行并进行排序。然后,我们可以转置输出并使用duplicated
确定重复项。由于duplicated
返回一个布尔值,因此我们将dat
中duplicated = FALSE
的所有行作为子集。
答案 1 :(得分:0)
library(igraph)
myList = lapply(split(dat, dat$V3), function(x) { # Split the data by third column
g1 = graph.data.frame(x, directed = FALSE) # create undirected graph
g2 = simplify(g1, remove.multiple = TRUE) # remove duplicates (same pairs)
get.edgelist(g2) #Convert to list of pairs
})
# Add the date back and then combine rows
do.call(rbind, lapply(names(myList), function(nm) data.frame(myList[[nm]], nm)))
# X1 X2 nm
#1 home cat date1
#2 fire water date2
#3 sofa TV date3
#4 kitchen knife date4