Compare matrices to find the differences

后端 未结 2 1349
感动是毒
感动是毒 2020-12-22 12:02

I have 2 matrices, I want to compare them (row.name wise) to find the difference.

> head(N1)
              Total_Degree Transitivity Betweenness Closeness         


        
2条回答
  •  一生所求
    2020-12-22 12:23

    That is a part of the solution, in res you have a data.table to work with for the difference part:

    require(data.table)
    require(dplyr)
    
    set.seed(2016)
    dt1 <- data.table(V1 = c("a", "b", "c", "d"), V2 = rnorm(4))
    dt2 <- data.table(V1 = c("c", "d", "e", "f"), V2 = rnorm(4))
    
    # common <- merge(dt1, dt2, by = "V1")[, Unique := "Common"]
    # unique1 <- dt1[V1 %nin% dt2[, V1], ][, Unique := "N1"]
    # unique2 <- dt2[V1 %nin% dt1[, V1], ][, Unique := "N2"]
    # res <- rbind(common, unique1, unique2, fill = TRUE)
    

    Small update after @Cath answer, just for clarity.

    allMerged <- merge(dt1, dt2, by = "V1", all = TRUE) %>%
      .[, RowSum := rowSums(.SD, na.rm = TRUE), .SDcols = grep("V2", names(.))] %>%
      .[, Unique := ((is.na(V2.x) + 2*is.na(V2.y)))]
    
    print(allMerged)
    

提交回复
热议问题