抑制 R 中 Tabyl xtabs 中的缺失值

Suppress missing values in Tabyl xtabs in R

According to the tabyl documentation:

但是,我不知道如何从分母中抑制 NA!

数据请看这里:

df <- data.frame(col1 = c(1,1,2,2,1, NA,NA),
                 col2 = c("this", NA,"is", "text",NA,NA,'yes'), 
                 col3 = c('TRUE', 'FALSE', NA, 'TRUE','TRUE', 'TRUE', 'FALSE'), 
                 col4 = c(2.5, 4.2, 3.2, NA, 4.2, 3.2,3)) %>% 
                  mutate_if(is.numeric, as.factor) %>% 
                  mutate_if(is.character, as.factor) 

str(df)  
df %>% 
  tabyl(col1, col3, show_missing_levels = F) %>% 
  adorn_percentages("row")%>% 
  adorn_pct_formatting(digits = 2) %>%
  adorn_ns()

请注意 NA 的百分比如何仍然显示在分母中。我根本不想在交叉表中看到 NA %:

 col1      FALSE       TRUE        NA_
    1 33.33% (1) 66.67% (2)  0.00% (0)
    2  0.00% (0) 50.00% (1) 50.00% (1)
 <NA> 50.00% (1) 50.00% (1)  0.00% (0)

我想看的:

 col1      FALSE       TRUE       
    1 33.33% (1) 66.67% (2)  
    2  0.00% (0) 100.00% (1)

知道如何实现吗?

默认情况下,tabyl 中的 show_na = TRUE。如果我们将其更改为 FALSE,OP 的代码应该可以工作

library(dplyr)
library(janitor)
 df %>% 
   tabyl(col1, col3, show_missing_levels = FALSE, show_na = FALSE) %>%
   adorn_percentages("row")%>% 
   adorn_pct_formatting(digits = 2) %>%
   adorn_ns()

-输出

#  col1      FALSE        TRUE
#    1 33.33% (1)  66.67% (2)
#    2  0.00% (0) 100.00% (1)

早些时候,正在考虑注入 na_omit 以删除 NA 行和 select 到 select 感兴趣的列。但是,这也会 changes/remove 属性,从而使 adorn_ns 不起作用

和akrun的差不多

library(dplyr)
library(janitor)
df %>% 
  tabyl(col1, col3, show_missing_levels = FALSE) %>% 
  na.omit() %>% 
  select(-NA_) %>%
  adorn_percentages("row")%>% 
  adorn_pct_formatting(digits = 0)  

输出:

 col1 FALSE TRUE
    1   33%  67%
    2    0% 100%