在 R 中的 wpct() (加权 table 百分比)的结果中包括零计数级别

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

我有一个与此类似的问题:Include levels of zero count in result of table() Yet, I'm not using table() but wpct() from the 'weights' 包。遗憾的是,为 table() 提供的解决方案不适用于 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 

有什么想法吗?谢谢!

我们可以使用 complete 来创建一个缺失的观察结果

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

-输出

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