How to combine two rows in R?

后端 未结 3 1530
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 10:33

I would like to combine/sum two rows based on rownames to make one row in R. The best route might be to create a new row and sum the two rows together.

Example df:<

3条回答
  •  耶瑟儿~
    2021-01-06 10:54

    You can replace the A row using the standard addition arithmetic operator, and then remove the C row with a logical statement.

    df["A", ] <- df["A", ] + df["C", ]
    df[rownames(df) != "C", ]
    #   V2 V3 V4 V5
    # A  7 11  5  8
    # B  3  2  7  9
    # D  3  2  8  9
    

    For more than two rows, you can use colSums() for the addition. This presumes the first value in nm is the one we are replacing/keeping.

    nm <- c("A", "C")
    df[nm[1], ] <- colSums(df[nm, ])
    df[!rownames(df) %in% nm[-1], ]
    

    I'll leave it up to you to change the row names. :)

    Data:

    df <- structure(list(V2 = c(1L, 3L, 6L, 3L), V3 = c(3L, 2L, 8L, 2L), 
        V4 = c(4L, 7L, 1L, 8L), V5 = c(6L, 9L, 2L, 9L)), .Names = c("V2", 
    "V3", "V4", "V5"), class = "data.frame", row.names = c("A", "B", 
    "C", "D"))
    

提交回复
热议问题