1

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!

TiF
  • 615
  • 2
  • 12
  • 24

1 Answers1

2

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thanks Arun Kirshna! :-) May I ask you a follow-up? If I use your code, it works perfectly fine. If I then replace 'test' and 'weight' with the actual variable names, I get an error message: Error: unexpected '=' in " complete(data.engl$Q03_3 =" Do you happen to know why? – TiF Aug 30 '21 at 20:52
  • @TiF it should be `data.engl$` instead it would be just `Q03_3` – akrun Aug 30 '21 at 20:53
  • i.e. `complete(Q03_3, ...` – akrun Aug 30 '21 at 20:53
  • super!! With attach(data.engl) before and detach(data.engl) after the code, it works nicely! Thanks!! – TiF Aug 30 '21 at 20:59
  • 1
    @TiF if it is a data.frame, you don't need attach i.e. `complete(data.engl, Q03_3, ...) or `data.engl %>% complete(Q03_3, ..` – akrun Aug 30 '21 at 21:04