% !TEX program = pdfLaTeX
% !TEX spellcheck = en_US

\documentclass[letterpaper,10pt]{article}
\usepackage[margin=.45cm]{geometry}

\usepackage{%
ragged2e,
graphicx,
multicol}

\columnseprule.3pt
\renewcommand{\baselinestretch}{.9}
\newenvironment{Hang}{\vskip-2ex\leftskip2em\parindent-2em\parskip-.1ex\mbox{}}{}

\pagestyle{empty}
\nofiles
\RaggedRight

\begin{document}

\textbf{\huge{One Page \textsf{R} Reference Card}}\hfill\textit{Alexey Shipunov, \today}

\begin{multicols}{2}

\vspace*{-3ex}

\begin{Hang}

\texttt{c(a, b)}: concatenate, vectorize \hfill \texttt{\#} comment char

\texttt{install.packages("package1")}: install package \texttt{package1}

\texttt{is.na(x1)}: \texttt{TRUE} if \texttt{x1 == NA}

\texttt{library(package1)}: load package \texttt{package1}

\texttt{NA}: missing value \hfill \texttt{3e3}: $3 \times 10^3 = 3000$ (e-notation)

\texttt{options(scipen=100)}: get rid of e-notation

\texttt{<-} or \texttt{assign()}: assign

\texttt{q("no")}: quit \textsf{R}, do not save environment

\texttt{history(Inf)}; \texttt{savehistory(file1)}: look on command history; save history (not on \textsf{macOS} GUI)

\texttt{;} used to separate commands \hfill \texttt{::} used as \texttt{package::command()}

\texttt{Tab}; \texttt{Up}; \texttt{Ctrl+U}: complete; repeat command; delete command (not on \textsf{macOS} GUI)

\end{Hang}

\smallskip\textbf{Help}

\begin{Hang}

\texttt{example(com1)}: run examples for command \texttt{com1}

\texttt{help(com1)} or \texttt{?com1}: help about command \texttt{com1}

\texttt{help(package=rpart)}: help for the package, e.g. \texttt{rpart}

\texttt{function1}; \texttt{methods(function2)}; \texttt{getAnywhere(method2)}:  look on the \texttt{function1} and \texttt{2} codes

\texttt{??"topic1"}: finds \texttt{topic1} in all help files (slow!)

\end{Hang}

\smallskip\textbf{Entering and saving data}

\begin{Hang}

\texttt{dir(...)} and \texttt{setwd()}: list files in directory, go to another

\texttt{read.table("file1", h=T, sep=";", as.is=T)}: read data into data frame from \texttt{file1} which has header and semicolon as separator; do not convert variables into factors 

\texttt{scan("file1", what="char"}: read one series of character codes from disk into variable

\texttt{sink("file1", split=TRUE)}: output to \texttt{file1} and to the terminal until \texttt{sink()}

\texttt{source("file1.r")}: run commands from file \texttt{file1.r}

\texttt{write.table(x1, "file1")}: write object \texttt{x1} to the file \texttt{file1}

\end{Hang}

\smallskip\textbf{Manage variables and objects}

\begin{Hang}

\texttt{1:3} or \texttt{c(1, 2, 3)}: \textbf{c}oncatenate \texttt{1, 2, 3} into vector

\texttt{as.data.frame(x1), as.matrix(x1)}: conversion

\texttt{cbind(a1, b1, c1)} or \texttt{rbind(a1, b1, c1)}: join columns or rows into matrix

\texttt{cut(v1, 2, labels=c("small", "big"))}: split vector \texttt{v1} in two intervals

\texttt{data.frame(v1, v2)}: list from same-length vectors \texttt{v1} and \texttt{v2}

\texttt{df1\$a1}: variable (column) named \texttt{a1} from data frame \texttt{df1}

\texttt{dimnames(mat1)}, or \texttt{names(df1)} and \texttt{row.names(df1)}: names of rows and columns of \texttt{mat1} or \texttt{df1}

\texttt{droplevels(factor1)}: drop unused factor levels

\texttt{grep("str1", x1)}: search \texttt{str1} in \texttt{x1}

\texttt{gsub("str1", "str2", x1)}: replace \texttt{str1} to the \texttt{str2} in \texttt{x1}

\texttt{head(df1)}: first rows of data frame

\texttt{length(v1)}, \texttt{nrow(mat1)}, \texttt{ncol(df1)}: sizes

\texttt{list1[[-5]]}: all list elements except 5th

\texttt{ls()}: list all active objects

\texttt{mat1[, 2:5]} or \texttt{mat1[, c(2, 3, 4, 5)]}: columns from 2nd to 5th

\texttt{matrix(vector1, r1, c1)}: transform \texttt{vector1} into matrix with \texttt{r1} rows and \texttt{c1} columns, columnwise

\texttt{merge(df1, df2)}: merge two data frames

\texttt{paste("cow", "boy", sep="")}: outputs \texttt{"cowboy"}

\texttt{rep(x1, n1)}: repeat vector~\texttt{x1 n1}~times

\texttt{sample(x1, n1)}: sample \texttt{n1} elements from \texttt{x1} without replacement

\texttt{seq(n1, n2, n3)}: sequence from \texttt{n1} to \texttt{n2} by \texttt{n3} steps

\texttt{stack()} and \texttt{unstack()}: convert from short to long form and back again

\texttt{str(obj1)}: structure of object \texttt{obj1}

\texttt{t(mat1)}: rotate $90^\circ$ matrix or data frame

\texttt{with(x1, ...)}: do something within \texttt{x1}

\end{Hang}

\smallskip\textbf{Cycles, conditions and functions}

\begin{Hang}

\texttt{for (i1 in sequence1) dosomething }: cycle

\texttt{fun1 <- function(args1) dosomething }: define function

\texttt{if (condition1) \dots else \dots}: single condition

\texttt{ifelse(condition1, yes, no)}: vectorized condition

\end{Hang}

\smallskip\textbf{Logic and math}

\begin{Hang}

\texttt{is.factor(obj1), is.atomic(obj1), is.data.frame(obj1)}: check the type of object \texttt{obj1}

\texttt{mat1[mat1 > 0]}: elements of \texttt{mat1} which are positive

\texttt{!<, \&, |, ==}: ``not less'', ``and'', ``or'', ``equal''

\texttt{cumsum(x1); diff(x1); prod(x1); sum(x1)}: vector math

\texttt{round(x1)}: round

\texttt{unique(x1)}: list unique elements of \texttt{x1} (could be sparse)

\texttt{*, \^{}, sqrt(pi), abs(-3), log(1)}: multiplication, degree, $\sqrt\pi$, \texttt{3}, natural logarithm

\texttt{x1 \%in\% x2}: which elements of \texttt{x1} are in \texttt{x2}

\texttt{which(logic1)}: indexes of all TRUE's

\end{Hang}

\smallskip\textbf{Descriptive statistics}

\begin{Hang}

\texttt{aggregate(...)}: pivot table

\texttt{apply(x1, n1, function)}: apply function to all rows (if \texttt{n1 $=1$}) or columns (\texttt{n1 $=2$}), output matrix

\texttt{colSums(mat1)}: calculate sums of every column

\texttt{rev(x1), order(x1), scale(x1), sort(x1)}: reverse, sorting indexes, scale and center, (ascending) sort

\texttt{sapply(); lapply(); do.call(); replicate()}: vectorize

\texttt{summary(x1); IQR(x1); fivenum(x1); mad(x1); max(x1); mean(x1); median(x1); min(x1); sd(x1); var(x1)}: descriptive statistics

\texttt{table(x1, x2)}: cross-tabulation

\texttt{tapply(x1, list1, f1)}: apply function \texttt{f1} to \texttt{x1} grouping by \texttt{list1}

\end{Hang}

\smallskip\textbf{Inferential statistics}

\begin{Hang}

\texttt{chisq.test(tab1)}: $\chi^2$-test for table \texttt{tab1}

\texttt{cor(df1)}: (Pearson) correlations between all columns of the data frame

\texttt{cor.test(x1, x2)}: (Pearson) correlation test

\texttt{ks.test(...); t.test(...), wilcox.test(...)}: other tests

\texttt{lm(...); glm(...); aov(...); anova(...)}: linear and non-linear models, analyses of variation (ANOVA)

\texttt{predict(model1)}: predict from model

\verb|lm(y ~ x + z, data=...)|: formula interface to the additive linear model, \texttt{y} responses on two variables, \texttt{x} and \texttt{z}

\end{Hang}

\smallskip\textbf{Multivariate statistics}

\begin{Hang}

\texttt{dist(...)}: distance calculation

\texttt{cmdscale(...)}: metric multidimensional scaling (MDA)

\texttt{hclust(...)}: hierarchical cluster analysis

\texttt{princomp(...); prcomp(...)}: principal component analyses (PCA)

\end{Hang}

\smallskip\textbf{Plots}

\begin{Hang}

\texttt{boxplot(...), dotchart(...), hist(...)}: useful plots

\texttt{identify(...)}: reveal information from points using mouse

\texttt{legend("topleft", legend="...")}: add legend to the top left corner

\texttt{lines(...); points(...); text(...)}: add lines, then points, then text

\texttt{pdf("file1.pdf")}: draw into \texttt{file1.pdf} until \texttt{dev.off()}

\texttt{oldpar <- par(mfrow=c(2,1))}: plots will be stacked until \texttt{par(oldpar)}

\texttt{oldpar <- par(mar=c(0,0,0,0))}: all plot margins set to zero until \texttt{par(oldpar)}

\texttt{plot(.., cex=1|2)}: normal dot size, double dot size

\texttt{plot(.., col=0|1|2|3)}: white, black, red, green color

\texttt{plot(.., lty=0|1|2)}: no lines, straight line, dashed line

\texttt{plot(.., type="p|l|s|n")}: \textbf{p}oints, \textbf{l}ines, \textbf{s}tairs and \textbf{n}o plot

\texttt{qqnorm(vec1); qqline(vec1)}: check normality

\end{Hang}

\end{multicols}

\texttt{plot(.., pch=..)}: \vtop{\vskip-2.5ex\includegraphics[width=.8\textwidth]{pch.pdf}}

\end{document}
