Mohamed Rahouma
Mohamed Rahouma

Reputation: 1236

How to report percentages by rows in createtableone command in tableone package?

I want to report percentage by rows using CreateTableOne from tableone package in r using the following code

vars<-c( "Group1vsGroup2", "Single.Institution",  
           "Internal.Funding",  "National.Funding", 
           "Industr1.Funding")

CatVar<-c(  "Single.Institution",  
           "Internal.Funding",  "National.Funding", 
           "Industr1.Funding")


tab2 <- CreateTableOne(vars = vars, strata = "Group1vsGroup2",factorVars = CatVar,data = df,test = T);tab2<-print(tab2, margin=1,test = T, varLabels = T,quote = T,dropEqual = T)

I added "margin=1" as I saw in this website although it was for tableone command (not CreateTableOne), but I got % by columns as in the image below. Any advice will be greatly appreciated. enter image description here

Upvotes: 3

Views: 2406

Answers (1)

A. Suliman
A. Suliman

Reputation: 13135

Here a MWE you can start with, see ?Gmisc::getDescriptionStatsBy for more details.

library(Gmisc)
# Define cyl as a factor so that getDescriptionStatsBy can use the correct Gmisc::describe*
mtcars$cyl=as.factor(mtcars$cyl)
getTable1Stats <- function(x, digits = 0,...){
  getDescriptionStatsBy(x = x, 
                        by = mtcars$am,
                        digits = digits,
                        header_count = TRUE,
                        ...)
}

t1 <- list()
t1[["Gas"]] <- getTable1Stats(mtcars$mpg, add_total_col="last")
#hrzl_prop=FALSE will indicate that the proportions are to be interpreted in a vertical manner
t1[["Cylinder&dagger;"]] <- getTable1Stats(mtcars$cyl, hrzl_prop=TRUE, add_total_col="last")
t1[["Disp"]] <- getTable1Stats(mtcars$disp, continuous_fn=describeMedian, add_total_col="last")

mergeDesc(t1,
  htmlTable_args = list(css.rgroup = "",
  caption  = "Basic descriptive statistics from the mtcars dataset",
  tfoot = "&dagger; The weight is in 10<sup>3</sup> kg")
)

enter image description here

PS: This solution based on Max's vignette here. For more details on htmlTable you can see its vignette here

Upvotes: 4

Related Questions