My R cheatsheet

Stuff I find myself Googling for the nth time

Get name of variable within function

deparse(substitute(x))

Padding numbers with leading zeroes

formatC(1:10, width = 3, flag = '0') 

Remove white space and extraneous characters from text

x <- '  abc <>?|!"£$%^&*()_+}{~@:¬}"  def  123'
gsub('\\W+', '', x)  # Gives "abc_def123"

Set contrasts

options(contrasts = rep('contr.treatment', 2))

Set reference level of factor

thedata[, newvar := relevel(factor(oldvar), 'Reference level here')]