R Code Snippets
Some useful R code for reuse
Graphics/output
- Draw grid behind histogram
- Create jittered dotplot with median lines with ggplot2
- Add a single main title to a multiplot
- Legend with expressions and values from variables
- Various ways of visualizing conditional distributions with ggplot2
- Wrap text on axis with stringr
- QQ-plot for non-normal distribution
- Paired plot for baseline and follow-up measurements
- Legend settings
- Survival: Plotting fitted parametric survivor functions
- Comparing discrete distributions using empirical CDF
- Points with error bars using base R
- Histogram with legend for bar and line
- Create animation with library(animation)
- Printing colored text on terminal
Vector and matrix manipulation
- Fill NAs with last non-NA values
- Insert values after specified indices
- Apply function to grouped data
- Compare the elements of two vectors
- Get duplicated elements from a vector
- Create AR(1) correlation matrix
- Count consecutive 1s in a vector
- Get the (non-main) diagonals of a matrix
- Converting integers to base 2 vectors
- Converting base 2 vectors to decimals with Reduce()
Functions
- Evaluate a function recursively using previous results
- Short-circuit evaluation
- Updating lm objects recursively to eliminate insignificant variables
- Extract model matrix and response vector using formula
- Calculate MLE of logit model using optim()
- Functions as inputs and outputs of other functions
Data handling and manipulation
- Match period beginnings to events in grouped data using rolling join in data.table
- Read data from an url with RCurl
- Transfrom values to a data frame to formatted text
Package specific
- survival: lagged time dependent covariates
- animation: creating animations and saving as gif
- data.table: rolling join
Simulations
- Approximating pi with Monte Carlo methods
- Reproducible parallel simulations
- Connection between Binomial and Poisson distributions
- Conway's Game of Life
- Wolfram's elementary cellular automata
- Using Poisson process to generate Poisson-distributed random sample
- Simulate continuous-time Markov chains
- Simulate M/M/s/c queues
- Posterior simulation using rejection sampling
Statistics
- Power curves, and determinants of the power of a test
- Calculate MLE of logit model using optim()
- Poisson regression with offset
- Setting contrasts for factors in lm()
- Likelihood: Comparing likelihood-based confidence intervals for binomial data
- Likelihood: Joint likelihood and profile likelihood
- Survival: Fitting parametric survival model
- Testing linear parameter restrictions in a normal linear regression model
- Bayesian: Logistic regression with Metropolis sampling
- Using Chi-square goodness-of-fit test to test discrete distribution
- Posterior simulation using rejection sampling
- Setting coding schemes for discrete ordinal covariates