Appendix VI. Overview of R Commands
Material of this appendix is based on the "cheat sheet" located on the official R project page, as well as its version.
Help
help(topic), ?topic — help on topic
help.search("pattern"), ??pattern — global search for pattern
help(package = ) — help on the specified package
help.start() — start help in browser
apropos(what) — names of objects matching what
args(name) — arguments of command name
example(topic) — examples of topic usage
Environment
ls() — list of all objects
rm(x) — remove object
dir() — show all files in current directory
getwd() — specify current directory
setwd(dir) — change current directory to dir
Object Overview
str(object) — internal structure of object object
summary(object) — general information about object object
dput(x) — get representation of object in R syntax
head(x) — look at initial rows of object
tail(x) — look at last rows of object
Input andoutput
library(package) — attach package package
save(file, ...) — saves specified objects in platform-independent binary XDR format
load() — loads data previously saved by save() command
read.table — reads data table and creates data.frame from it
write.table — prints object, converting it to data.frame
read.csv — reads csv file
read.delim — reads data separated by tab characters
save.image — saves all objects to file
cat(..., file= , sep= ) — saves arguments, concatenating them through sep
sink(file) — outputs results of other commands to file in real-time mode until the same command is called without arguments
Object Creation
from:to — generates sequence of numbers from from to to with step 1, e.g., 1:3
c(...) — combines arguments into vector, e.g., c(1, 2, 3)
seq(from,to,by = ) — generates sequence of numbers from from to to with step by
seq(from,to,len = ) — generates sequence of numbers from from to to of length len
rep(x, times) — repeats x times times
list(...) — creates list of objects
data.frame(...) — creates data frame
array(data, dims) — creates multidimensional array from data with dimensions dim
matrix(data, nrow = , ncol = ,byrow = ) — creates matrix nrow by ncol from data, fill order determined by byrow
factor(x, levels = ) — creates factor from x with levels levels
gl(n, k, length = n*k, labels = 1:n) — creates factor with n levels, each repeated k times of length length with labels labels
rbind(...) — combines arguments by rows
cbind(...) — combines arguments by columns
Indexing
Vectors
x[n] — nth element
x[-n] — all elements except nth
x[1:n] — first n elements
x[-(1:n)] — all elements except first n
x[c(1,4,2)] — elements with listed indices
x["name"] — element with specified name
x[x > 3] — all elements greater than 3
x[x > 3 & x < 5] — all elements between 3 and 5
x[x %in% c("a","and","the")] — all elements from specified set
Lists
x[n] — list consisting of element n
— nth element of list
name — list element with name name
x$name — list element with name name
Matrices
x[i, j] — element at intersection of ith row and jth column
x[i,] — ith row
x[,j] — jth column
x[,c(1,3)] — specified subset of columns
x["name", ] — row with name name
Data Frames
name — column with name name
x$name — column with name name
Working with Variables
as.array(x), as.data.frame(x), as.numeric(x), as.logical(x), as.complex(x), as.character(x) — convert object to specified type
is.na(x), is.null(x), is.array(x), is.data.frame(x), is.numeric(x), is.complex(x), is.character(x) — check if object belongs to specified type
length(x) — number of elements in x
dim(x) — dimensions of object x
dimnames(x) — dimension names of object x
names(x) — names of object x
nrow(x) — number of rows of x
ncol(x) — number of columns of x
class(x) — class of object x
unclass(x) — extracts class attribute from object x
attr(x,which) — attribute which of object x
attributes(obj) — list of attributes of object obj
Data Management
which.max(x) — index of element with maximum value
which.min(x) — index of element with minimum value
rev(x) — reverses order of elements
sort(x) — sorts elements of object in increasing order
cut(x,breaks) — divides vector into equal intervals
match(x, y) — finds elements of x that are in y
which(x ==a) — returns indices of elements of x that equal a
na.omit(x) — excludes missing values (NA) from object (in matrix or frame excludes corresponding row)
na.fail(x) — returns error message if object contains NA
unique(x) — excludes repeated elements from object
table(x) — creates table with count of each unique element
subset(x, ...) — returns subset of elements of object corresponding to specified condition
sample(x, size) — returns random sample of size from elements of x
replace(x, list, values) — replaces values of x with indices from list with values values
append(x, values) — adds elements values to vector x
Mathematics
sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), atan2(y, x), log(x), log(x, base), log10(x), exp(x) — elementary mathematical functions
min(x), max(x) — minimum and maximum elements of object
range(x) — vector of minimum and maximum elements of object
pmin(x, y), pmax(x, y) — returns vector with minimum (maximum) values for each pair x[i], y[i]
sum(x) — sum of elements of object
prod(x) — product (result of multiplication) of elements of object
diff(x) — returns vector of differences between adjacent elements
mean(x) — arithmetic mean of elements of object
median(x) — median of object
weighted.mean(x, w) — weighted mean of object x (w specifies weights)
round(x, n) — rounds x to n decimal places
cumsum(x), cumprod(x), cummin(x), cummax(x) — cumulative sums, products, minima and maxima of vector x (ith element contains statistics on elements x[1:i])
union(x, y), intersect(x, y), setdiff(x,y), setequal(x,y), is.element(el,set) — set operations: union, intersection, difference, membership
Re(x), Im(x), Mod(x), Arg(x), Conj(x) — operations on complex numbers: real part, imaginary part, modulus, argument, conjugate
fft(x), mvfft(x) — fast Fourier transform
choose(n, k) — number of combinations
rank(x) — ranks elements of object
Matrices
%*% — matrix multiplication
t(x) — transposed matrix
diag(x) — diagonal of matrix
solve(a, b) — solves system of equations a %*% x = b
solve(a) — inverse matrix
colSums, rowSums, colMeans, rowMeans — sums and means by columns and rows
Data Reshaping
apply(X,INDEX,FUN =) — returns vector, array or list of values obtained by applying function FUN to certain elements of array or matrix x; elements to be processed are specified using MARGIN argument;
lapply(X,FUN) — returns list of the same length as x; values in new list will be result of applying function FUN to elements of original object x
tapply(X,INDEX,FUN =) — applies function FUN to each group of values of x created according to levels of certain factor; list of factors is specified using INDEX argument
by(data,INDEX,FUN) — analog of tapply(), applied to data tables
merge(a,b) — combines two data tables (a and b) by common columns or rows
aggregate(x,by,FUN) — splits data table x into separate data sets, applies certain function FUN to these sets and returns result in readable format
stack(x, ...) — transforms data represented in object x as separate columns into data table
unstack(x, ...) — performs operation inverse to stack() function
reshape(x, ...) — transforms data table from "wide format" (repeated measurements of any variable recorded in separate columns) to "narrow format" table (repeated measurements go one after another within single column)
Date and Time
as.Date(s) — converts vector s to object of class Date
as.POSIXct(s) — converts vector s to object of class POSIXct
Strings
print(x) — prints x to screen
sprintf(fmt, ...) — C-style text formatting (can use %s, %.5f, etc.)
format(x) — formats object x so that it looks nice when printed to screen
paste(...) — converts vectors to text variables and combines them into one text expression
substr(x,start,stop) — substring extraction
strsplit(x,split) — splits string x into substrings according to split
grep(pattern,x) (also grepl, regexpr, gregexpr, regexec) — regular expression search
gsub(pattern,replacement,x) (also sub) — regular expression replacement
tolower(x) — convert string to lowercase
toupper(x) — convert string to uppercase
match(x,table), x %in% table — finds elements in vector table that match values from vector x
pmatch(x,table) — finds elements in vector table that partially match values from vector x
nchar(x) — returns number of characters in string x

Graphics
plot(x) — plot of x
plot(x, y) — plot of y versus x
hist(x) — histogram
barplot(x) — bar chart
dotchart(x) — Cleveland diagram
pie(x) — pie chart
boxplot(x) — box-and-whisker plot
sunflowerplot(x, y) — same as plot(), but points with identical coordinates are depicted as "sunflowers", number of petals proportional to number of such points
coplot(x˜y | z) — plot of y versus x for each interval of values of z
interaction.plot(f1, f2, y) — if f1 and f2 are factors, this function will create plot with mean values according to values of f1 (on x-axis) and f2 (on y-axis, different curves)
matplot(x, y) — plot of columns of y versus columns of x
fourfoldplot(x) — depicts (as sectors of circle) association between two binary variables in different populations
assocplot(x) — Cohen-Friendly plot
mosaicplot(x) — mosaic plot of residuals from log-linear regression
pairs(x) — if x is matrix or data table, this function will plot scatter diagrams for all possible pairs of variables from x
plot.ts(x), ts.plot(x) — plots time series
qqnorm(x) — quantiles
qqplot(x, y) — plot of quantiles of y versus quantiles of x
contour(x, y, z) — performs data interpolation and creates contour plot
filled.contour(x, y, z) — same as contour(), but fills areas between contours with certain colors
image(x, y, z) — depicts data as squares, color determined by values of x and y
persp(x, y, z) — same as image(), but as three-dimensional plot
stars(x) — if x is matrix or frame, depicts plot as "stars" such that each row is represented by a "star", and columns determine length of rays of these "stars"
symbols(x, y, ...) — depicts various symbols according to coordinates
termplot(mod.obj) — depicts partial effects of variables from regression model
Individual Plot Elements
points(x, y) — draw points
lines(x, y) — draw lines
text(x, y, labels, ...) — add text label
mtext(text, side=3, line=0, ...) — add text label
segments(x0, y0, x1, y1) — add line segment
arrows(x0, y0, x1, y1, angle= 30, code=2) — draw arrow
abline(a,b) — draw sloped line
abline(h=y) — draw vertical line
abline(v=x) — draw horizontal line
abline(lm.obj) — draw regression line
rect(x1, y1, x2, y2) — draw rectangle
polygon(x, y) — draw polygon
legend(x, y, legend) — add legend
title() — add title
axis(side, vect) — add axes
rug(x) — draw ticks on x-axis
locator(n, type = "n", ...) — returns coordinates on plot in response to user click
Lattice Graphics
xyplot(y˜x) — plot of y versus x
barchart(y˜x) — bar chart
dotplot(y˜x) — Cleveland diagram
densityplot(˜x) — density plot of values of x
histogram(˜x) — histogram of values of x
bwplot(y˜x) — box-and-whisker plot
qqmath(˜x) — analog of qqnorm() function
stripplot(y˜x) — analog of stripplot(x) function
qq(y~x) — depicts quantiles of distributions of x and y for visual comparison of these distributions; variable x must be numeric, variable y — numeric, text, or factor with two levels
splom(~x) — matrix of scatter diagrams (analog of pairs() function)
levelplot(z~xy|g1g2) — color plot of values of z, coordinates given by variables xand y (obviously x, yand zmust have same length); g1, g2 ... (if present) — factors or numeric variables whose values are automatically divided into equal intervals
wireframe(z~xy|g1g2) — function for building three-dimensional scatter diagrams and surfaces; z, xand yare numeric vectors; g1, g2 ... (if present) — factors or numeric variables whose values are automatically divided into equal intervals
cloud(z˜xy|g1g2) — three-dimensional scatter diagram
Optimization and Parameter Fitting
optim(par, fn, method = ) — general-purpose optimization
nlm(f,p) — minimization of function f by Newton algorithm
lm(formula) — linear model fitting
glm(formula,family=) — generalized linear model fitting
nls(formula) — nonlinear least squares
approx(x,y=) — linear interpolation
spline(x,y=) — cubic spline interpolation
loess(formula) — polynomial surface fitting
predict(fit,...) — make predictions
coef(fit) — estimated coefficients
Statistics
sd(x) — standard deviation
var(x) — variance
cor(x) — correlation matrix
var(x, y) — covariance between xand y
cor(x, y) — linear correlation between xand y
aov(formula) — analysis of variance
anova(fit,...) — analysis of variance for fitted models fit
density(x) — kernel density estimates
binom.test() — exact test of simple hypothesis about probability of success in Bernoulli trials
pairwise.t.test() — pairwise comparisons of several independent or dependent samples
prop.test() — test of hypothesis about equality of proportions of certain characteristic in all analyzed groups
t.test() — Student's t-test
Distributions
rnorm(n, mean=0, sd=1) — normal distribution
rexp(n, rate=1) — exponential distribution
rgamma(n, shape, scale=1) — gamma distribution
rpois(n, lambda) — Poisson distribution
rweibull(n, shape, scale=1) — Weibull distribution
rcauchy(n, location=0, scale=1) — Cauchy distribution
rbeta(n, shape1, shape2) — beta distribution
rt(n, df) — Student's t distribution
rf(n, df1, df2) — Fisher's F distribution
rchisq(n, df) — Pearson's chi-squared distribution
rbinom(n, size, prob) — binomial distribution
rgeom(n, prob) — geometric distribution
rhyper(nn, m, n, k) — hypergeometric distribution
rlogis(n, location=0, scale=1) — logistic distribution
rlnorm(n, meanlog=0, sdlog=1) — lognormal distribution
rnbinom(n, size, prob) — negative binomial distribution
runif(n, min=0, max=1) — uniform distribution
Programming
Working with Functions
function(arglist) { expr } — creates user-defined function
return(value) — returns value
do.call(funname, args) — calls function by name
Conditional Statements
if(cond) expr
if(cond) cons.expr else alt.expr
ifelse(test, yes, no)
Loops
for(var in seq) expr
while(cond) expr
repeat expr
break — stop loop