Search code examples
rcrosstabcranperformanceanalytics

Add a row with the sum of each colum in a table in R


I'm creating a cross table of 2 factors that has inside the sum of another variable

b<-xtabs(utib~qpl+i , data=data ) 

This give me a table like

                   <=2.5 2.5-5 5-10 10-50 50-150   150-250   >250     NA
  aaaa               3231   211   64    10      1       0    0       32
  bbbbbbbbb          442    78    7      3      0       0    0        5
  cccccc             6462   466   76     6      0       0    0      157

I need to add in the last row the sum of each column I need that it keeps 'table class' because then I have to export it with the code:

   library(PerformanceAnalytics))
    win.metafile(file)    
    PerformanceAnalytics:::textplot(c)
    dev.off()

Solution

  • You can use the addmargin() function

    #sample data
    data<-data.frame(
       utib=rpois(50,10), 
       qpl=sample(letters[1:3], 50, replace=T),
       i=cut(runif(50,0,250), breaks=c(0,2.5,5,10,50,150))
    )
    
    (b<-xtabs(utib~qpl+i , data=data ) )
    
    #    i
    # qpl (0,2.5] (2.5,5] (5,10] (10,50] (50,150]
    #   a       0      12     24      46       53
    #   b       0       0      0       0      100
    #   c       0       0      0      46       42
    
    (bb<-addmargins(b, margin=1))
    
    #    i
    # qpl   (0,2.5] (2.5,5] (5,10] (10,50] (50,150]
    #   a         0      12     24      46       53
    #   b         0       0      0       0      100
    #   c         0       0      0      46       42
     #  Sum       0      12     24      92      195