Search code examples
rsummarygtsummary

How to change column order in tbl_summary() in R


I am using tbl_summary in R to create a table, but I do not like the default ordering of the columns.

```
tbl9 <- DH_df2 %>% select(Age_Group, BOP_Level)
tbl9 %>%
  tbl_summary(by = Age_Group,
  missing = "no") %>%
  add_p(everything() ~ "chisq.test") %>%
  modify_header(label ~ "**Age Groups**") %>%
  modify_caption("**Table 1. Correlation Age and BOP**") %>%
  bold_labels()
```

My output gives me the correct information and table, but I want to move "Under 35" to be the come before "Age36~50". How can I do that?

Current Column output: Age Groups / Age36~50 / Age51~ / Under 35 / p-value


Solution

  • The easiest way to define the order of the by variable levels is to make your by variable a factor with the levels in the order you'd like them to appear.

    PS if you provide reproducible examples in your posts (i.e. code we can all run on our machines), you'll get more detailed solutions.