rsummarizationgroup-summaries

How to summarize rows and columns in R?


I have this kind of table:

           aaa     bbb   ccc 
  A         0       3     5    
  B         2       2     2    
  C         2       5     7

I get it using anti_join (for a table with non numeric values) and table command to group the result in a nicer way (something like countif in Excel).

da1 <- anti_join(data1,data2, by=c("pam1","pam2"))
table(da1$pam1,da1$pam2)

I was wondering if is possible to add also a Sum of each row and each column, so that in the result there will be something like this:

           aaa     bbb   ccc  SUM 
  A         0       3     5    8
  B         2       2     2    6
  C         2       5     7    14
 SUM        4      10     14

Solution

  • We can try with rowSums and colSums

    cbind(rbind(df, SUM = rowSums(df)), SUM = c(colSums(df), NA))
    
    #     aaa bbb ccc SUM
    #A     0   3   5   4
    #B     2   2   2  10
    #C     2   5   7  14
    #SUM   8   6  14  NA