Giter VIP home page Giter VIP logo

summarizer's Introduction

summarizer

The summarizer package provides functions that help you create elegant final results tables and charts when modelling. Its design follows Hadley Wickham's tidy tool manifesto.

Installation and Documentation

You can install summarizer from github with:

# install.packages("devtools")
devtools::install_github("ewenharrison/summarizer")

It is not a dependent, but it is recommended that this package is used together with dplyr which can be installed via:

install.packages("dplyr")

To install off-line (or in a Safe Haven), download the zip file and use devtools::install_local().

Main Features

1. Summarise variables/factors by a categorical variable

summary.factorlist() is a simple wrapper used to summarise any number of variables by a single categorical variable. This is usually "Table 1" of a study report. The categorical variable can have a maximum of five levels.

library(summarizer)
library(dplyr)

# Load example dataset, modified version of survival::colon
data(colon_s)

# Table 1 - Patient demographics ----
explanatory = c("age", "age.factor", "sex.factor", "obstruct.factor")
dependent = "perfor.factor"
colon_s %>%
  summary.factorlist(dependent, explanatory, p=T)

summary.factorlist() is also commonly used to summarise any number of variables by an outcome variable (say dead yes/no).

# Table 2 - 5 yr mortality ----
explanatory = c("age.factor", "sex.factor", "obstruct.factor", "perfor.factor")
dependent = 'mort_5yr'
colon_s %>%
  summary.factorlist(dependent, explanatory)

Tables can be knitted to PDF, Word or html documents. We do this in RStudio from a .Rmd document. Example chunk:

knitr::kable(example_table, row.names=FALSE, align=c("l", "l", "r", "r", "r"))

2. Summarise regression model results in final table format

The second main feature is the ability to create final tables for logistic glm(), hierarchical logistic lme4::glmer() and Cox proprotional hazard survival::coxph() regression models.

The summarizer() "all-in-one" function takes a single dependent variable with a vector of explanatory variable names (continuous or categorical variables) to produce a final table for publication including summary statistics, univariable and multivariable regression analyses. The first columns are those produced by summary.factorist().

e.g. glm(depdendent ~ explanatory, family="binomial")

explanatory = c("age.factor", "sex.factor", "obstruct.factor", "perfor.factor")
dependent = 'mort_5yr'
colon_s %>%
  summarizer(dependent, explanatory)

Where a multivariable model contains a subset of the variables specified in the full univariable set, this can be specified.

explanatory = c("age.factor", "sex.factor", "obstruct.factor", "perfor.factor")
explanatory.multi = c("age.factor", "obstruct.factor")
dependent = 'mort_5yr'
colon_s %>%
  summarizer(dependent, explanatory, explanatory.multi)

Random effects.

e.g. lme4::glmer(dependent ~ explanatory + (1 | random_effect), family="binomial")

explanatory = c("age.factor", "sex.factor", "obstruct.factor", "perfor.factor")
explanatory.multi = c("age.factor", "obstruct.factor")
random.effect = "hospital"
dependent = 'mort_5yr'
colon_s %>%
  summarizer(dependent, explanatory, explanatory.multi, random.effect)

metrics=TRUE provides common model metrics.

colon_s %>%
  summarizer(dependent, explanatory, explanatory.multi,  metrics=TRUE)

Cox proportional hazards

e.g. survival::coxph(dependent ~ explanatory)

explanatory = c("age.factor", "sex.factor", "obstruct.factor", "perfor.factor")
dependent = "Surv(time, status)"

colon_s %>% 
	summarizer(dependent, explanatory)

Rather than going all-in-one, any number of subset models can be manually added on to a summary.factorlist() table using summarizer.merge(). This is particularly useful when models take a long-time to run or are complicated.

Note requirement for glm.id=TRUE. fit2df is a subfunction extracting most common models to a dataframe.

explanatory = c("age.factor", "sex.factor", "obstruct.factor", "perfor.factor")
explanatory.multi = c("age.factor", "obstruct.factor")
random.effect = "hospital"
dependent = 'mort_5yr'

# Separate tables
colon_s %>%
  summary.factorlist(dependent, explanatory, glm.id=TRUE) -> example.summary

colon_s %>%
  glmuni(dependent, explanatory) %>%
  fit2df(estimate.suffix=" (univariable)") -> example.univariable

colon_s %>%
  glmmulti(dependent, explanatory) %>%
  fit2df(estimate.suffix=" (multivariable)") -> example.multivariable


colon_s %>%
  glmmixed(dependent, explanatory, random.effect) %>%
  fit2df(estimate.suffix=" (multilevel") -> example.multilevel

# Pipe together
example.summary %>% 
  summarizer.merge(example.univariable) %>% 
  summarizer.merge(example.multivariable) %>% 
  summarizer.merge(example.multilevel) %>% 
  select(-c(glm.id, index)) -> example.final
example.final

Cox Proportional Hazards example with separate tables merged together.

explanatory = c("age.factor", "sex.factor", "obstruct.factor", "perfor.factor")
explanatory.multi = c("age.factor", "obstruct.factor")
dependent = "Surv(time, status)"

# Separate tables
colon_s %>%
	summary.factorlist(dependent, explanatory, glm.id=TRUE) -> example2.summary

colon_s %>%
	coxphuni(dependent, explanatory) %>%
	fit2df(estimate.suffix=" (univariable)") -> example2.univariable

colon_s %>%
  coxphmulti(dependent, explanatory.multi) %>%
  fit2df(estimate.suffix=" (multivariable)") -> example2.multivariable

# Pipe together
example2.summary %>% 
	summarizer.merge(example2.univariable) %>% 
	summarizer.merge(example2.multivariable) %>% 
	select(-c(glm.id, index)) -> example2.final
example2.final

3. Summarise regression model results in plot

Models can be summarized with odds ratio/hazard ratio plots using or.plot or hr.plot (hr.plot not fully tested).

# OR plot
explanatory = c("age.factor", "sex.factor", "obstruct.factor", "perfor.factor")
dependent = 'mort_5yr'
colon_s %>%
  or.plot(dependent, explanatory)
# Previously fitted models (`glmmulti()` or `glmmixed()`) can be provided directly to `glmfit`  
  
# HR plot (not fully tested)
explanatory = c("age.factor", "sex.factor", "obstruct.factor", "perfor.factor")
dependent = "Surv(time, status)"
colon_s %>%
  hr.plot(dependent, explanatory, dependent_label = "Survival")
# Previously fitted models (`coxphmulti`) can be provided directly using `coxfit`

Our own particular Rstan models are supported and will be documented in the future. Broadly, if you are running (hierarchical) logistic regression models in Stan with coefficients specified as a vector labelled beta, then fit2df() will work directly on the stanfit object in a similar manner to if it was a glm or glmerMod object.

4. Kaplan-Meier survival plots

KM plots can be produced using the library(survminer)

# KM plot
explanatory = c("perfor.factor")
dependent = "Surv(time, status)"
colon_s %>% 
  surv.plot(dependent, explanatory, xlab="Time (days)", pval=TRUE, legend="none")

Notes

Use Hmisc::label() to assign labels to variables for tables and plots.

label(colon_s$age.factor) = "Age (years)"

Export dataframe tables directly or to R Markdown using knitr::kable().

Note wrapper summary.missing() can be useful. Wraps mice::md.pattern.

colon_s %>%
  summary.missing(dependent, explanatory)

summarizer's People

Contributors

davidhen avatar ewenharrison avatar tomdrake avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

summarizer's Issues

New error from Hmisc namespace

New error:

Error: 'summary.formula' is not an exported object from 'namespace:Hmisc'

Fix:

Add ':::' in front of summary.formula (see my fork)

Synthetic data?

Hi Ewen,
I'm hoping to get this package installed in the National Safe Haven in Edinburgh.
The eDRIS team have a query re the raw data - is it synthetic?
I know the colon.R data comes from the survival package so no problems there, but (I think) the query may be to do with the hospitals data.
Thanks
David

Random effects in Summarizer

I love this.

There is a small bug when specifying random_effects in summarizer. The option 'random_effect' to function summarizer() looks by default to an object called 'random_effects' which is outside the function.

Changing line 20 and 22 from random_effects to random_effect resolves the issue in summarizer.R

On here for record keeping.

glm code tweak

Hello - Not one to rush into - I'll test over next couple of weeks, but as an update I've rewritten a few of the glm functions to be able to handle weights and potentially new families in models (so these are compatible with propensity score matching.

It produces the same glmlist model (albeit with a more accurate call per dependent variable).

I'll work on it a bit and see if it errors at all. Posted for the record!

Example:

glmmulti <- function(df.in, dependent, explanatory, weights = NULL, family = "binomial"){ result = list() if (is.null(weights)){ for (i in 1:length(dependent)) { f <- as.formula(paste(dependent, '~', paste(explanatory, collapse="+"))) fit <- do.call("glm", list(formula=f, data=df.in, family= family)) fit['call'] = deparse(f) result[[i]] <- fit} } else { for (i in 1:length(dependent)) { f <- as.formula(paste(dependent, '~', paste(explanatory, collapse="+"))) fit <- do.call("glm", list(formula=f, data=df.in, family= family, weights = weights)) fit['call'] = deparse(f) result[[i]] <- fit} } result = setNames(result, dependent) class(result) = "glmlist" return(result) }

Further modelling

Just another thing to remind myself to do this along the way...

Write in 'hidden' elements/ functions to extract the models so simulation and predicting can be done off of models summarizer

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.