Search code examples
rsurvey

How to get the percentage of the frequency table in survey package


I'm working on a complex survey. I'm trying to use svytable to do the contingency table. I used the following code:

(tbl <- svytable(~sch.wide+stype, dclus1))

result
        stype
sch.wide         E         H         M
     No   406.1640  101.5410  270.7760
     Yes 4467.8035  372.3170  575.3989

I want to have the percentage of each cell in the table. something like the following,

      stype
sch.wide         E         H         M
     No   406.1640(xx%)  101.5410(xx%)  270.7760(xx%)
     Yes 4467.8035(xx%)  372.3170(xx%)  575.3989(xx%)

Any help is appreciated


Solution

  • One simple approach would be to just replace the values of the table object with the original values and the proportions using paste0():

    library(survey)
    data(api)
    xtabs(~sch.wide+stype, data=apipop)
    dclus1<-svydesign(id=~dnum, weights=~pw, data=apiclus1, fpc=~fpc)
    tbl <- svytable(~sch.wide+stype, dclus1)
    
    tbl[] <- paste0(round(tbl, 2), " (", round(prop.table(tbl)*100, 2), "%)")
    tbl
    
            stype
    sch.wide E               H              M             
         No  406.16 (6.56%)  101.54 (1.64%) 270.78 (4.37%)
         Yes 4467.8 (72.13%) 372.32 (6.01%) 575.4 (9.29%)