How to sort by frequency the result of 'CreateTableone' when you have many variables?

Viewed 23
Hospital<-c("AA","BB","BB","CC","BB",
          "AA", "CC", "BB", "CC", "DD")
`Disease stage`<-c("3","2","2","3","2","1","2","3","2","2")
Location<-c("B","A","B","A","C","B","B","B","C","A")

mydata<-data.frame(Hospital,`Disease stage`,Location)


library(tableone)

CreateTableOne(data = mydata)


n                 10        
  Hospital (%)                
     AA              2 (20.0) 
     BB              4 (40.0) 
     CC              3 (30.0) 
     DD              1 (10.0) 
  Disease.stage (%)           
     1               1 (10.0) 
     2               6 (60.0) 
     3               3 (30.0) 
  Location (%)                
     A               3 (30.0) 
     B               5 (50.0) 
     C               2 (20.0) 

I want to order the categories according to their frequencies for each variable. Is this possible directly with CreateTableone?

1 Answers

The output is a list object.

> str(out1)
List of 3
 $ ContTable: NULL
 $ CatTable :List of 1
  ..$ Overall:List of 3
  .. ..$ Hospital     :'data.frame':    4 obs. of  7 variables:
  .. .. ..$ n          : int [1:4] 10 10 10 10
  .. .. ..$ miss       : int [1:4] 0 0 0 0
  .. .. ..$ p.miss     : num [1:4] 0 0 0 0
  .. .. ..$ level      : chr [1:4] "AA" "BB" "CC" "DD"
  .. .. ..$ freq       : 'table' int [1:4(1d)] 2 4 3 1
  .. .. ..$ percent    : 'table' num [1:4(1d)] 20 40 30 10
  .. .. ..$ cum.percent: num [1:4] 20 60 90 100
  .. ..$ Disease.stage:'data.frame':    3 obs. of  7 variables:
  .. .. ..$ n          : int [1:3] 10 10 10
 ...

So, we could use lapply to loop over the object and order based on the 'freq' column and update the object by assigning back

out1$CatTable$Overall <- lapply(out1$CatTable$Overall, \(x) x[order(x$freq),])

-output

 out1
                   
                    Overall   
  n                 10        
  Hospital (%)                
     DD              1 (10.0) 
     AA              2 (20.0) 
     CC              3 (30.0) 
     BB              4 (40.0) 
  Disease.stage (%)           
     1               1 (10.0) 
     3               3 (30.0) 
     2               6 (60.0) 
  Location (%)                
     C               2 (20.0) 
     A               3 (30.0) 
     B               5 (50.0) 

where

out1 <- CreateTableOne(data = mydata)
Related