Search code examples
rtidyverserow

Sum two rows with numeric values


In this picture, I want to add the values of the two "Rural municipality" to make them one. I don't seem to know how to do this.

table


Solution

  • It is also possible with base R. One possible approach is to set the discriminating string of rows to be added to the same value and aggregate by this string.

    Example with a builtin dataset:

    > s <- apply(Titanic, c("Class","Survived"), sum)
    > x <- data.frame(Class=rownames(s), No=s[,"No"], Yes=s[,"Yes"])
    > x$Class <- as.character(x$Class)
    > x
         Class  No Yes
    1st    1st 122 203
    2nd    2nd 167 118
    3rd    3rd 528 178
    Crew  Crew 673 212
    

    To combine (sum) the two rows of 1st and 2nd class, we first assign them a new identical Class name, and then aggregate by Class:

    > x[x$Class %in% c("1st","2nd"), "Class"] <- "upper"
    > aggregate(. ~ Class, data=x, FUN=sum)
      Class  No Yes
    1   3rd 528 178
    2  Crew 673 212
    3 upper 289 321