0

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
Ale
  • 645
  • 4
  • 16
  • 38

2 Answers2

2

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
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Layout is perfect, but if I try to apply it to a real table, the sum values are incorrect – Ale Feb 12 '17 at 09:00
  • @Ale Do you have any `NA` values in there. The above solution works on the sample data provided. You should add an example which represents your real data. – Ronak Shah Feb 12 '17 at 09:02
  • no, there is no NA, i mean it is very similar to an example above, but it gives a Warning: number of rows of result is not a multiple of vector length (arg 2) – Ale Feb 12 '17 at 09:14
1

An elegant option is addmargins

addmargins(as.matrix(df1))
#    aaa bbb ccc Sum
#A     0   3   5   8
#B     2   2   2   6
#C     2   5   7  14
#Sum   4  10  14  28

data

df1 <- structure(list(aaa = c(0L, 2L, 2L), bbb = c(3L, 2L, 5L), ccc = c(5L, 
2L, 7L)), .Names = c("aaa", "bbb", "ccc"), class = "data.frame", row.names = c("A", 
"B", "C"))
akrun
  • 874,273
  • 37
  • 540
  • 662