MDStat
MDStat

Reputation: 435

Use summary(CreateTableOne) in HTML Output

I use the CreateTableOne function to create a table for descriptive statistics - as an example I used the mtcars dataset (and modified two variables to a factor to simulate categorical variables).

library(tableone)

mydata <- mtcars

mydata$gear <- as.factor(mydata$gear)
mydata$carb <- as.factor(mydata$carb)

VarsForTableOne <- c("mpg", "cyl", "disp", "hp", "drat", "wt", "gear", "carb")

myTableOne <- CreateTableOne(vars = VarsForTableOne, data = mydata, strata = "vs")
summary(myTableOne)

myTableOne$ContTable
myTableOne$CatTable

Now I would like to get a table for the data with continuous aspects (min, mean, median, max, quartiles) and categorical data (percentage) with each characteristics per variable.

summary(myTableOne) generates all the information which is interesting for me, but myTableOne$ContTable and myTableOne$CatTable not enough. Is there a way to customize the output of CreateTableOne?

In the end I would like to get a table which can be formatted as HTML in a Markdown and/or copied to Excel.

Thanks for any help!

Upvotes: 0

Views: 960

Answers (1)

Dan Chaltiel
Dan Chaltiel

Reputation: 8523

I'm not sure about {tableone} but here is a solution using the package {crosstable}.

Disclaimer: I'm the author of this package.

library(crosstable)
mydata <- mtcars
mydata$gear <- as.factor(mydata$gear)
varsForDescription <- c("mpg", "cyl", "gear")

crosstable(mydata, cols=any_of(varsForDescription), 
           by=vs, test=TRUE) %>% 
   as_flextable()
#> Warning: Be aware that automatic global testing should only be done in an exploratory context, as it would cause extensive alpha inflation otherwise.
#> This warning is displayed once every 8 hours.

crosstable output Created on 2021-10-24 by the reprex package (v2.0.1)

You can fully customize which summary function to use on continuous variables (for instance, try funs=c(mean=mean, "std error"=sd)) and how percentages are calculated (for instance, try margin=c("row", "col")).

Here, I'm using flextable() to output an HTML table that you can embed in RMarkdown or MS Word, but I could have used as_workbook() to output an openxlsx workbook that you can export to Excel.

You can read more about this in the documentation, there are many other features that might be of interest.

Upvotes: 1

Related Questions