[R] Append the sum of each row and column to a table matrix

Marc Schwartz marc_schwartz at comcast.net
Sun Sep 30 21:15:03 CEST 2007


On Sun, 2007-09-30 at 20:56 +0200, Tom Cohen wrote:
> Dear list, 
>   I have following table
>    
>   ee<-table(ID,Day)
>   ee
>       Day
>   ID    2  3  4 5 6  7  9 10 14 16
>     35  5  0  0 3 1  0  0  5  0  0
>     36  0  0  0 0 0  0  0  1  0  0
>     43 13 15 15 0 0 13 13 15 13 15
>     46  0  1  0 0 0  0  0  0  0  0
>     58  0  0  0 0 0  0  4  4  0  0
>   and want to calculate the sum for each row and column and then
> append the sums to the table matrix.
>    
>   kk<cbind(ee,as.matrix(apply(ee,1,sum)))
>   dd<-rbind(kk,apply(ee,2,sum))
>    
>   Warning message:
>   number of columns of result
>           is not a multiple of vector length (arg 2) in: rbind(1, kk,
> apply(ee,2, sum))
>    
>   rownames(dd)<-c(rownames(dd)[-6],"Total:")
>   colnames(dd)<-c(colnames(dd)[-11],"Total:")
>    
>   I got a table as wanted (see below), except that the variable names
> Day and ID are missing. Is there a way to add back these variable
> names to the table "dd" as shown in "ee". Also I got a warning message
> that I'm not exactly know how to skip. Can I make the table "dd" in a
> different and easier way ? Any suggestions are highly appreciated.
>    
>   Thanks,
>   Tom
>    
>   dd
>    
>           2  3  4 5 6  7  9 10 14 16 Total:
>   35      5  0  0 3 1  0  0  5  0  0     14
>   36      0  0  0 0 0  0  0  1  0  0      1
>   43     13 15 15 0 0 13 13 15 13 15    112
>   46      0  1  0 0 0  0  0  0  0  0      1
>   58      0  0  0 0 0  0  4  4  0  0      8
>   Total: 18 16 15 3 1 13 17 25 13 15     18
>    

The easiest way to do this is to use addmargins():

dd <- addmargins(ee, FUN = list(Total = sum), quiet = TRUE)

> dd
       Days
ID        2   3   4   5   6   7   9  10  14  16 Total
  35      5   0   0   3   1   0   0   5   0   0    14
  36      0   0   0   0   0   0   0   1   0   0     1
  43     13  15  15   0   0  13  13  15  13  15   112
  46      0   1   0   0   0   0   0   0   0   0     1
  58      0   0   0   0   0   0   4   4   0   0     8
  Total  18  16  15   3   1  13  17  25  13  15   136



See ?addmargins for more information.

HTH,

Marc Schwartz



More information about the R-help mailing list