Compare matrices to find the differences

后端 未结 2 1356
感动是毒
感动是毒 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:35

    A way to go in base R, with rowSums and merge:

    If N1 and N2 are data.frames:

    # compute the row sums and merge N1 and N2
    N1$rs <- rowSums(N1, na.rm=TRUE)
    N2$rs <- rowSums(N2, na.rm=TRUE)
    comp <- merge(N1[, "rs", drop=FALSE], N2[, "rs", drop=FALSE], by="row.names", all=TRUE)
    
    # then compare the row sums and the variable "locations"
    comp$Unique <- with(comp, c("N1", "N2", "common")[(!is.na(rs.x)) + 2*(!is.na(rs.y))])
    comp$Comparison <- with(comp, rs.x-rs.y)
    
    # keep only the variable you need:
    comp <- comp[, c(1, 5, 4)]
    

    If N1 and N2 are matrices:

    # compute the row sums and merge N1 and N2
    rs1 <- rowSums(N1, na.rm=TRUE)
    rs2 <- rowSums(N2, na.rm=TRUE)
    comp <- merge(N1, N2, by="row.names", all=TRUE)
    
    # then compare the row sums and the variable "locations"
    comp$Unique <- with(comp, c("N1", "N2", "common")[as.numeric(!is.na(Total_Degree.x)) + 2*as.numeric(!is.na(Total_Degree.y))])
    comp$Comparison <- with(merge(as.data.frame(rs1), as.data.frame(rs2), all=TRUE, by="row.names"), rs1-rs2)
    
    # keep only the variable you need:
    comp <- comp[, c("Row.names", "Comparison", "Unique")]
    

    output of both methods:

    comp
    #      Row.names    Comparison Unique
    #1 2410016O06RIK  0.0000844042 common
    #2          ADI1            NA     N2
    #3          AGO1 -1.8332483856 common
    #4          AIRN            NA     N2
    #5         APEX1  3.0000856324 common
    #6           ATR  0.8334181369 common
    #7         CASP3            NA     N1
    #8         CCND2            NA     N1
    

提交回复
热议问题