I have a data frame that contains duplicated values in two columns.
dat<-data.frame(V1 = c(\"home\",\"cat\",\"fire\",\"sofa\",\"kitchen\",\"sofa\"),
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
dat[!duplicated(t(apply(dat, 1, sort))),]
Using apply
and sort
will loop through each row and sort. We can then transpose the output and determine duplicates using duplicated
. Because duplicated
returns a boolean we then subset all rows in dat
where duplicated = FALSE
.