Search code examples
rcountfrequencymissing-dataweighted

Include levels of zero count in result of wpct() (weighted table of percentages) in R


I have a problem similar to this one: Include levels of zero count in result of table() Yet, I'm not using table() but wpct() from the 'weights' package. Sadly, the solution provided for table() does not work with wpct():

test <- c(1,1,1,1,1,1,2,2,2,3,3,3,5,5)
weight <- c(.5,.5,.5,.5,.5,1,1,1,1,2,2,2,2,2)

wpct(test, weight)
#        1         2         3         5 
#0.2121212 0.1818182 0.3636364 0.2424242

wpct(factor(test, levels = 0:5), weight)
#        1         2         3         5 
#0.2121212 0.1818182 0.3636364 0.2424242 

Any ideas? Thanks!


Solution

  • We could use complete to create a missing observation

    library(dplyr)
    library(tidyr)
    library(weights)
    tibble(test, weight) %>% 
       complete(test = 1:5, fill = list(weight = 0)) %>% 
       summarise(out = wpct(test, weight))
    

    -output

    # A tibble: 5 x 1
        out
      <dbl>
    1 0.212
    2 0.182
    3 0.364
    4 0    
    5 0.242