Title: R

Q: Distribution functions
A: pdf: d[](x, mean = 0, sd = 1, log = FALSE)
cdf: p[](q, mean = 0, sd = 1, lower.tail = TRUE, log.p = FALSE)
cdfinv: q[](p, mean = 0, sd = 1, lower.tail = TRUE, log.p = FALSE)
rv: r[](n, mean = 0, sd = 1)
log.p: if TRUE, probabilities p are given as log(p).
lower.tail:  if TRUE (default), probabilities are $\P[X \leq x]$ otherwise, $\P[X > x]$.
[] = norm, chisq, unif, f, t, pois etc.

Q: Rounding
A: decimal: round(x, digits=0)
sf: signif(x, digits=6)
floor(x)
ceiling(x)

Q: Concatenate and print
A: cat(... , file = "", sep = " ", fill = FALSE, labels = NULL,
    append = FALSE)
concatenates, separates with sep, outputs to console/file, returns None (invisible NULL)
fill: if TRUE line width is option width, if numeric: line width.
labels: for each line (for fill not FALSE).
append: If TRUE output will be appended (rather than overwritten) to named file

Q: Create vector
A: combine: c(...)
repeat: rep(x, times=1):
sequence: seq(from=1, to=1, by = ((to - from)/(length.out - 1)), length.out = NULL):
simple sequence from:to

Q: Ternary operator
A: ifelse(test, yes, no)

Q: Create matrix
A: matrix(data=NA, nrow=1, ncol=1, byrow=FALSE, dimnames=NULL)
dimnames: list(rowNameVec, colNameVec)

Q: List
A: list(el1=var1, el2)
slicing: [] (for accessing copies)
member reference: [[1]] (for modifying)

Q: Concatenate strings
A: paste (..., sep = " ", collapse = NULL)
paste0(..., collapse = NULL)
sep: separator
collapse: separator for vector input

Q: Plotting
A: plot(y$\sim$x, data=data)
plot(data\$x, data\$y)
plot(model)
barplot(height, ...)
par(mfrow=c(2,2)): 2x2 multiple plot
points(x, y)
lines(x,y)
barplot(heights)

Q: Straight line plot
A: abline(a = NULL, b = NULL, h = NULL, v = NULL, reg = NULL,
       coef = NULL, untf = FALSE, ...)
y=a+bx
coef=c(a,b)
y=h
x=v

Q: Cook’s distance and leverage
A: hatvalues(model, ...)
cooks.distance(model, ...)
which(hatvalues $> 3p/n$)

Q: Import data
A: df $<$- read.csv(filename)
attach(df)

Q: Confidence/prediction intervals
A: coefficients: confint(model, parm, level=0.95)
parm: subset of parameters
A $p\times 2$ matrix of confidence limits. Column labels (1-level)/2  and 1 - (1-level)/2 in \%.
predict(linmod, newrow, interval = c("none", "confidence", "prediction"), type=c("response", "link", "terms"), level = 0.95)
Vector of predictions. For intervals: matrix with columns fit, lwr, and upr if interval is set.

Q: Analysis of variance
A: anova(model1, model2)
Columns: $n-p$, $\|(I-P)Y\|^2$, $p-p_0$, $\|(P-P_0)Y\|^2$, F stat, $p$-value
Add test="LR" for GLMs

Q: Design matrix
A: model.matrix($~x_1+x_2$, dataframe)
model.matrix(model)

Q: Box-Cox
A: boxcox(linmod, lambda = seq(-2, 2, 1/10), plotit = TRUE,
       interp=(length(lambda)<100), eps = 1/50, xlab = expression(lambda),
       ylab = "log-Likelihood", ...)
interp: whether spline interpolation is used.
eps: Tolerance for lambda = 0; defaults to 0.02.
Finds transformation power $\lambda$ to maximise profile likelihood.

Q: Dimensions
A: dim(x) = c(nrow(x), ncol(x))

Q: Factor
A: factor(...)
levels(...)
relevel(factor, "Level1")

Q: Finding interactions
A: interaction.plot(x.factor, trace.factor, response, fun = mean,
                 type = c("l", "p", "b", "o", "c"), legend = TRUE,
                 trace.label = deparse(substitute(trace.factor)),
                 fixed = FALSE,
                 xlab = deparse(substitute(x.factor)),
                 ylab = ylabel,
                 ylim = range(cells, na.rm = TRUE),
                 lty = nc:1, col = 1, pch = c(1:9, 0, letters),
                 xpd = NULL, leg.bg = par("bg"), leg.bty = "n",
                 xtick = FALSE, xaxt = par("xaxt"), axes = TRUE,
                 ...)
Compute fun of response across range of x for different traces. Parallel lines correspond to independence.

Q: Stepwise selection
A: stepAIC(initmodel, scope, scale = 0,
        direction = c("both", "backward", "forward"),
        trace = 1, steps = 1000,
        k = 2, ...)
scope: list(lower.formula, upper.formula) or just upper.formula
trace: amount of printing during run
steps: max steps
k=log(n) for BIC

Q: Generalised linear model fit
A: glm(formula, family = c(gaussian, binomial, poisson), data, trainingsubset,
    na.action, start = NULL, etastart, mustart, offset,
    control = list(...), model = TRUE, method = "glm.fit",
    x = FALSE, y = TRUE, contrasts = NULL, ...)
attributes: coefficients, deviance, null.deviance

Q: Logical operators
A: $! x$
$x \& y$
$x | y$
xor($x$, $y$)
isTRUE($x$)

Q: Information criteria
A: AIC(model, k=2)
BIC(model)

Q: Apply Functions
A: Apply FUN to \textbf{each} element of
matrix: apply(X, MARGIN=c(1,2), FUN, ...)
list: lapply(X, FUN, ...)
list: sapply(X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE). simplify gives a matrix if possible
list: vapply(X, FUN, FUN.VALUE=c(row1name=0, ...), ..., USE.NAMES = TRUE). Specify output template.
multiple vectors: mapply(FUN, vec1, vec2..., MoreArgs = list(other FUN args), SIMPLIFY = TRUE,
       USE.NAMES = TRUE)
replicate(n, expr, simplify = "array"). Wrapper for sapply. Put n*expr into a matrix.

Q: Aggregate dataframe
A: aggregate(x, by=factorAsList, FUN=mean, ..., simplify = TRUE, drop = TRUE)
Split rows of x into levels of by and compute FUN

Q: Combine by row/column
A: cbind, rbind

Q: Contingency tables
A: table(data)
xtabs(Freq $\sim$ x + y, data=data)