Herman Bjornstad
Herman Bjornstad

Reputation: 23

How to determine column order when using the table1 function

I am making a table with the table1 function, however it automatically arranges the rows alphabetically.I cant share the data unfortunately, but my current code looks something like this;

table1(~ Running + Sitting + Yelling + drinking + Smoking | subject_condition, data=SDD)

I need to order the subject contrition columns in a specific way. I would greatly appreciate any help!! Thank you Kindly :)

My data looks kinda like this: enter image description here

The output has the columns by alphabetical order; Alabastor then Carlings then Bohemia. How do i edit the code so that the columns are arranged like this: Bohemia then carlings, then Alabastor?

Thank you!

Upvotes: 1

Views: 1752

Answers (3)

mrbrich
mrbrich

Reputation: 891

Here is a solution that uses the mappings package. I've simulated some data to use for illustration.

library(table1)
library(mappings)

# Simulate sample data
set.seed(123)
SDD <- expand.grid(Participant=1:4, subject_condition=c("Alabastor", "Carlings", "Bohemia"))
SDD$Running  <- sample(1:12, nrow(SDD), replace=T)
SDD$Sitting  <- sample(1:12, nrow(SDD), replace=T)
SDD$Yelling  <- sample(1:12, nrow(SDD), replace=T)
SDD$drinking <- sample(1:12, nrow(SDD), replace=T)
SDD$Smoking  <- sample(1:12, nrow(SDD), replace=T)


column_order <- mapping(c("Bohemia", "Carlings", "Alabastor"))

table1(~ Running + Sitting + Yelling + drinking + Smoking | column_order(subject_condition), data=SDD)

example table result

Upvotes: 0

Haley Huston
Haley Huston

Reputation: 41

You've got to factor the data in the respective column before you put it in table1; or you can do within table1.

table1(
data = datatable %>%
mutate(subjectcc = factor(subjectcc, levels = c("Alabastor",
"Carlings", "Bohemia"), ordered = T),
~Running +
Yelling +
Sitting +
Drinking +
Smoking | .... )

Upvotes: 1

Mike
Mike

Reputation: 4400

Here is an example using the iris data set and using the gtsummary package. Initially species is in alphabetical order (first table) but if you refactor the variable it will appear in the order you like.

library(gtsummary)



tbl_summary(iris,
            by = "Species")

iris2 <- iris %>% 
          mutate(Species = factor(Species, levels =  c("versicolor", "setosa","virginica")))


tbl_summary(iris2,
            by = "Species")

Upvotes: 1

Related Questions