Elliott Chinn
Elliott Chinn

Reputation: 207

How to Replace Variable with Level in tbl_summary

A reviewer asked that rather than have both genders listed in the table, to just include one. So, Gender would be replaced with Female and the proportions of the gender that was female would be under each Treatment.

library(gtsummary)
d<-tibble::tribble(
      ~Gender, ~Treatment,      
      "Male", "A",
      "Male", "B", 
      "Female", "A",
      "Male", "C",
      "Female", "B",
      "Female", "C")

d %>% tbl_summary(by = Treatment)

Upvotes: 0

Views: 295

Answers (2)

Statistican
Statistican

Reputation: 43

For dichtomous variables, the tbl_summary() function provides the option to display only one category by using the type argument. The following code provides the solution. It correctly considers the total N.

library(gtsummary)
d<-tibble::tribble(
      ~Gender, ~Treatment,      
      "Male", "A",
      "Male", "B", 
      "Female", "A",
      "Male", "C",
      "Female", "B",
      "Female", "C")

d %>% tbl_summary(
  by    = Treatment, 
  # declare Gender as dichotomous variable
  type  = list(Gender ~ 'dichotomous'), 
  # set the value to show
  value = list(Gender ~ 'Female'), 
  # by default as characteristic still "Gender" is shown, change to "Female"
  label = list(Gender ~ 'Female'))

The output:

tbl_summary() output

Upvotes: 1

Mike
Mike

Reputation: 4400

One way to do this would be to remove the first row of table_body and only keep the second row of table_body this will only keep the information on Female. This matches your table you provided in the comments.

library(gtsummary)
d<-tibble::tribble(
  ~Gender, ~Treatment,      
  "Male", "A",
  "Male", "B", 
  "Female", "A",
  "Male", "C",
  "Female", "B",
  "Female", "C")

t1 <- d %>% filter(Gender == "Female") %>% tbl_summary(by = Treatment)



t1$table_body <- t1$table_body[2,]

t1

enter image description here

Upvotes: 0

Related Questions