benjaminrich / table1

79 stars 26 forks source link

Remove "Missing" row for select categorical variables #94

Closed chitrams closed 1 year ago

chitrams commented 1 year ago

I'd like to remove the "Missing" rows from the following table for the variables alcgp and tobgp only, and subsequently exclude the missing values from the percentage calculation for these variables.

Screenshot 2022-11-23 090700

I used the esoph data from datasets and randomly added missing values. Here's the data and code:

d <- esoph

# Randomly add missing values in data
set.seed(35)
d <- as.data.frame(lapply(d, function(cc) cc[ sample(c(TRUE, NA), prob = c(0.85, 0.15), size = length(cc), replace = TRUE) ]))

# Create table
table1(~ agegp + alcgp + tobgp, data = d)

I'm aware I can use the options render.missing = NULL and render.categorical = "FREQ (PCTnoNA%)" (thanks to issue #21!), but this removes the "Missing" row for all three variables. If there's a way to select which one (or more) variable(s) I can remove the "Missing" row for, that would be great.

Thank you!

benjaminrich commented 1 year ago

It is possible, using the following custom render function:

rndr <- function(x, name, ...) {
    if (name %in% c("alcgp", "tobgp")) {
        render.default(x, name, render.missing=NULL, render.categorical = "FREQ (PCTnoNA%)", ...)
    } else {
        render.default(x, name, ...)
    }
}

# Create table
table1(~ agegp + alcgp + tobgp, data = d, render=rndr)

image

chitrams commented 1 year ago

Thank you so much! This custom render function is exactly what I'm looking for.

The reprex I used here isn't the best example for what this feature would be used for. This feature is useful in instances where, for example, the variables are "Number of cases" and "Number of tobacco use for cases" in the one table. The missing values for "Number of tobacco use for cases" would be irrelevant as this is the number of non-cases (which would be shown in the "Number of cases" variable).

Would this custom render function be worth integrating into future versions of the table1 function?

Thank you again for your help, I really appreciate it. Great work on this package--it's my favourite for creating tables.