Home > Mobile >  How to sort frequencies in CreateTableOne
How to sort frequencies in CreateTableOne

Time:12-18

Here is a representation of my dataset

mydata<-data.frame(ID=1:37,var=c(rep("A",12),rep("B",8),rep("C",17)))

I calculated the frequency of each modality of the variable var

library(tableone)

CreateTableOne(data = mydata["var"])

What I want is to sort the frequencies in decreasing way, like below:

          Overall   
  n       37        
  var (%)        
     C    17 (45.9)    
     A    12 (32.4) 
     B     8 (21.6) 

CodePudding user response:

Change the factor levels to be in decreasing order of frequency.

library(tableone)

mydata2 <- transform(mydata, var = factor(var, names(sort(-table(var)))))
CreateTableOne("var", data = mydata2)

giving:

          Overall   
  n       37        
  var (%)           
     C    17 (45.9) 
     A    12 (32.4) 
     B     8 (21.6) 
  •  Tags:  
  • r
  • Related