njtierney / naniar

Tidy data structures, summaries, and visualisations for missing data
http://naniar.njtierney.com/
Other
650 stars 54 forks source link

Ensure repeated levels of recode_shadow works #273

Closed njtierney closed 3 years ago

njtierney commented 3 years ago

Description

This PR adds a catch condition for shadow_expand_relevel, which is called by recode_shadow to create the extra special missing levels.

Related Issue

Should fix #272

Example

library(tidyverse)
library(naniar)

df_sh <- data.frame(Q1 = c("yes", "no", "no", NA), 
                 Q2 = c("a", NA, NA, NA), 
                 Q3 = c(1, NA, NA, 4)) %>% 
  mutate(Q1 = factor(Q1)) %>% 
  mutate(Q2 = factor(Q2)) %>% 
  nabular()

# Q1 is a filter question - people who answer no should skip Q2 and Q3
df_sh_recode_q2 <- df_sh %>% 
  recode_shadow(Q2 = .where(Q1 %in% "no" ~ "skip"))

df_sh_recode_q3 <- df_sh_recode_q2 %>% 
  recode_shadow(Q3 = .where(Q1 %in% "no" ~ "skip"))

# there are empty factor levels ..
df_sh_recode_q3$Q1_NA %>% table(., useNA = "always")
#> .
#>     !NA      NA NA_skip    <NA> 
#>       3       1       0       0
df_sh_recode_q3$Q2_NA %>% table(., useNA = "always")
#> .
#>     !NA      NA NA_skip    <NA> 
#>       1       1       2       0
df_sh_recode_q3$Q3_NA %>% table(., useNA = "always")
#> .
#>     !NA      NA NA_skip    <NA> 
#>       2       0       2       0

Created on 2020-09-22 by the reprex package (v0.3.0)

Tests

Yes

NEWS + DESCRIPTION