Search code examples
rfrequencyweightedprop

How to show zeros in weighted table with r function wtable?


I appreciate the function wtable in GDAtools package like e.g.

GDAtools::wtable(mtcars$cyl,mtcars$gear,weights = mtcars$qsec, stat='freq')
        3     4     5   Sum
4    20,0 156,9  33,6 210,5
6    39,7  70,7  15,5 125,8
8   205,7        29,1      
Sum 265,4        78,2  

But this shows blank instead of zero for the cyl==8 & gear==4 combination. Thus I cannot use the prop option:

GDAtools::wtable(mtcars$cyl,mtcars$gear,weights = mtcars$qsec, stat='prop')
    3 4 5 Sum
4            
6            
8            
Sum   

Also not with prop.table:

prop.table(GDAtools::wtable(mtcars$cyl,mtcars$gear,weights = mtcars$qsec))
    3 4 5 Sum
4            
6            
8            
Sum  

Only rprop and cprob for rows and/or columns without blanks do work:

GDAtools::wtable(mtcars$cyl,mtcars$gear,weights = mtcars$qsec, stat='rprop')
       3    4    5 Sum
4    9,5 74,5 16,0 100
6   31,5 56,2 12,3 100
8     NA   NA   NA  NA
Sum   NA   NA   NA  NA
GDAtools::wtable(mtcars$cyl,mtcars$gear,weights = mtcars$qsec, stat='cprop')
        3  4     5 Sum
4     7,5 NA  43,0  NA
6    14,9 NA  19,8  NA
8    77,5 NA  37,2  NA
Sum 100,0 NA 100,0  NA

Ìs there a way to force zero instead of blank in wtable?


Solution

  • The blank values are actually NA values displayed differently. You can capture them with is.na.

    tab <- GDAtools::wtable(mtcars$cyl,mtcars$gear, weights=mtcars$qsec, stat='freq')
    tab[is.na(tab)] <- 0
    tab
    
    #        3     4     5   Sum
    #4    20.0 156.9  33.6 210.5
    #6    39.7  70.7  15.5 125.8
    #8   205.7   0.0  29.1   0.0
    #Sum 265.4   0.0  78.2   0.0