Home > Back-end >  How to change column order in tbl_summary() in R
How to change column order in tbl_summary() in R

Time:07-25

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

CodePudding user response:

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 I. Your posts (i.e. code we can all run on our machines), you'll get more detailed solutions.

CodePudding user response:

https://statisticsglobe.com/reorder-columns-of-data-frame-in-r

These are the basic methods (taken from above link).

  • use the indexing operator:
    data[ , c(2, 1, 3)] with index
    data[ , c("x2", "x1", "x3")] with names
  • use subset:
    subset(data, select = c(2, 1, 3))
  • use dplyrs select function:
    data %>% select(x2, x1, x3)

CodePudding user response:

You can use relocate function from the dplyr package.

library(dplyr)
tbl9 <- tbl9 %>%
relocate(` Under 35`, .before = `Age36~50`)
  • Related