Find unique pairs of words ignoring their order in two columns in R

前端 未结 2 1863
说谎
说谎 2020-12-22 11:17

I have a data frame that contains duplicated values in two columns.

   dat<-data.frame(V1 = c(\"home\",\"cat\",\"fire\",\"sofa\",\"kitchen\",\"sofa\"), 
          


        
相关标签:
2条回答
  • 2020-12-22 11:23
    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
    
    0 讨论(0)
  • 2020-12-22 11:38

    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.

    0 讨论(0)
提交回复
热议问题