When using the table function and sorting by variable, how to exclude a subcategory

39 Views Asked by At

I am making a table function where I am sorting by gender. However, I would like the no answer values, which are marked as a string to be omitted from the table. As it stands when the table prints, I have an male, female and no answer category, but not a single participant put no answer, so it's just a bunch of zeros

I've included a tibble of the data, I'm looking at the variable gender, which includes a no answer answer, which no one selected.

# A tibble: 321 × 2
   poverty            Gender
   <fct>              <fct> 
 1 Below Poverty Line Female
 2 Below Poverty Line Female
 3 Above              Female
 4 Below Poverty Line Female
 5 Above              Female
 6 Below Poverty Line Male  
 7 Above              Female
 8 Above              Female
 9 Above              Female
10 Above              Female
# ℹ 311 more rows

I've put the code below, but cannot figure out how to change the sorting function

testable1 <- nosingleparent %>% 
  select(qa3_gender, imp_race, qopmpov)
testable1 %>% 
  tbl_summary(by = qa3_gender) %>%
  modify_spanning_header(c("stat_1", "stat_2") ~ "**Gender**") %>%
  add_overall() %>%
  add_n() %>%
  modify_caption("**Table 3. Non-Single Parents in Study**") %>%
  modify_footnote(
    all_stat_cols() ~ "1 = Male and 2 = Female"
  ) 

I tried the code below but it didn't change any of the chart output

testable1 <- nosingleparent %>%
  filter(qa3_gender != "No Answer") %>%
  select(qa3_gender, imp_race, qopmpov)

enter image description here

1

There are 1 best solutions below

1
zephryl On

Hard to say for sure without sample data, but it sounds like qa3_gender is likely a factor that includes a "No Answer" level. This level will be included even if it doesn’t have any instances in your data. To avoid this, you’ll need to remove the unwanted level. One way to do this is using forcats::fct_drop():

library(dplyr)
library(forcats)

testable1 <- nosingleparent %>%
  mutate(qa3_gender = fct_drop(qa3_gender)) %>%
  select(qa3_gender, imp_race, qopmpov)