R Expressions - Operators - Arithmetic Functions
In and Out of R - Handling Data Types, Objects, and more
General Object | Classes and Methods | Vectors | Matrices | Arrays | Frames | Lists | Functions | Expressions | Environment | Formatting and Printing | Listing and Loading Libraries | Time, Time ... TimeMathematical Diversions - Theoretical Statistical Distributions
Creating Data Randomly | Missing Values in Given Data | Univariate Description | Bi- and Multivariate Description | Elementary Statistical Tests | Statistical Modelling and Evaluation | Time Series Devices | Set, Query, or View Colors | Set or Query Parameters | Plot and Add Graphical Elements | One-Dimension Plots | Two-Dimension Plots | Three-Dimension Plots | Graphical Input Functions | Control Flow | Interaction with the User | Listing and Loading Libraries | Foreign Function Interface | Tracing and Debugging | Time, Time ... Time | Prepare PublicationWindowsXX: Click, click ...
quit(), q() - Terminate an R-Session.
help(), ?(), help.start() - Show online access to
documentation
?topic, help(data), help(package), help("function")
- Specific help
data() - List all available data sets; data(set) - Load specific data set
library() - List all available packages
library(name, ...), require(name, ...), provide(name)
- Load specific package
ls(), objects() - Show the names of actually available
objects
apropos(pattern, ...) - Find Objects by Partial
Name
str(object, ...) - Compactly display the structure of
an arbitrary \R object
also: str.data.frame(object, ...),
str.default(object, ...), ls.str(name, pattern, ...), lsf.str(...)
args(fun) - Argument list of a function; fun - See list of the program
Machine() , machine()
- Show Info on numeric characteristics of the machine R is running on
options() - Sets and examines a variety of global
"options" how R computes and displays its results
gc() - Garbage Collection; shows memory use statistics -
gcinfo(verbose)
Version()
- Provides detailed information about the version of R running
license() - Show terms of R
system("command") - Execute Shell-Command, simply the mightiest command of R ;-)
Built-In Constants: LETTERS, letters, month.abb, month.name, pi
Relational: x < y; x > y; x <= y; x >= y; x == y; x != y
Logical: ! x - not; x & y - and; x && y - and; x | y - or; x || y - or; xor(x,y) - exclusive or
Useful: abs(x) ; sign(x) ; sqrt(x)
Logarithms and Exponentials:
log(x) - natural logarithm;
log10(x) - common logarithm;
log2(x) - binary logarithm
log(x, base) - general form of logarithm;
exp(x) - exponential function
Trigonometric:
sin(x) - sine;
cos(x) - cosine;
tan(x) - tangent
asin(x) - arc-sine;
acos(x) - arc-cosine;
atan(x) - arc-tangent;
atan2(y, x) - arc-tangent of two arguments
Hyperbolic: Versions of the above: cosh(x), sinh(x), tanh(x), acosh(x), asinh(x), atanh(x)
Beta and Gamma:
beta(a, b) and
lbeta(a, b) - beta function and its
natural logarithm.
gamma(a) and
lgamma(a) - gamma function and its
natural logarithm.
The functions digamma(a) ,
trigamma(a) ,
tetragamma(a) , and
pentagamma(a)
- first, second, third
and fourth derivatives of the logarithms of the gamma function.
Combinatorial:
prod(...) - Product of Vector Elements;
cumprod(1:n) - n!, n factorial
choose(n, k) and
lchoose(n, k) - binomial coefficients and
their logarithms.
fix(x) - Fix an Object
Command File In: source("filename") - redirect Input from file until it ends
Screen Output to File: sink(file) - Send \R Output to a file; sink() - ends the diversion
save(...,) - Save \R Objects
load(filename) - Reload Saved Datasets
write(x, file="data") - data x are written to file
dump(list, fileout="dumpdata")
- takes list names
of \R objects and produces text representations of the objects in the given
file
tempfile(pattern = "file") - Create Unique Names
for (Temporary) Files
unlink(x) - Delete Files
Invoke a System Command:
system("command") - execute Shell-Command,
simply the mightiest command of R ;-)
Classes and Methods
class(x), class <- names - Object Classes -
unclass(x), inherits(x, name)
UseMethod(name), NextMethod(name, object, ...),
methods(generic.function, class) - Class Methods
data.class(x) - Object Classes
Vectors
Creation
vector(...) - Vector Types;
mat.or.vec(nr, nc) - Create a Matrix or a Vector
c(...) - Combine Values into a Vector or List;
A kind of a beginning
: - Sequence Generation -
seq(from, to, ...)
rep(x, times, length.out) - Replicate Elements
sequence(nvec) - Create A Vector of Sequences
replace(x, list, values) - Replace Values in a
Vector
append(x, values, after=length(x)) - Vector Merging
match(x, table, ...) - Value Matching -
x %in% table
subset(x, ...), subset.data.frame, subset.default - Subsetting vectors and data frames
[.noquote, noquote(obj), print.noquote(obj, ...) - Class for "no quote" Printing of Strings
order(...) - Ordering Permutation;
aperm(a, perm, ...) - Array Transposition
sort(x,...) - Sort a Vector
rank(x) - Sample Ranks
outer(x, y, ...) - Outer Product of Vectors
Matrices
matrix(..., nrow, ncol) - Create a Matrix;
mat.or.vec(nr, nc) - Create a Matrix or a Vector
row(x, ...) - Row Indexes
col(x, ...) - Column Indexes
rownames(x), rownames(x) <- namevector
Row Labels
colnames(x), colnames(x) <- namevector
Column Labels
drop(x) - Drop Redundant Extent Information
Combine Rows rbind(...) / Columns
cbind(...) into a Matrix
nrow(x), ncol(x), NROW(x), NCOL(x) - The Number of
Rows/Columns of an Array
lower.tri(x, ...), upper.tri(x, ...) - Lower and
Upper Triangular Part of a Matrix
diag(x, nrow, ncol), diag(x) <- value - Matrix
Diagonals
aperm(a, perm, ...) - Array Transposition
t(x) - Matrix Transpose
crossprod(x, ...) - Matrix Crossproduct
outer(x, y, ...) - Outer Product of Vectors
scale(x, ...) - Scaling and Centering of Matrices
apply(x, MARGIN, FUN, ...) - Apply Functions Over Array Margins
Arrays
array(x, dim=dim) - Multi-way Arrays
dim(x), dim(x) <- values - Array Extents
dimnames(x), dimnames(x) <- nlist - Array Labels
drop(x) - Drop Redundant Extent Information
nrow(x), ncol(x), NROW(x), NCOL(x) - The Number of
Rows/Columns of an Array
aperm(a, perm, ...) - Array Transposition
apply(x, MARGIN, FUN, ...) - Apply Functions Over
Array Margins
sweep(x, MARGIN, STATS, FUN="-", ...) - Sweep out
Array Summaries
tapply(x, INDEX, ...) - Apply a Function Over a
"Ragged" Array
Frames
data.frame(...), as.data.frame(x), is.data.frame(x),
row.names(data.frame.object),
print(data.frame.obj) - Data Frames
nrow(x), ncol(x), NROW(x), NCOL(x) - The Number of
Rows/Columns of an Array
subset(x, ...), subset.data.frame, subset.default
- Subsetting vectors and data frames
transform(x, ...), transform.data.frame(),
transform.default - Transform an Object, e.g. a dataframe
data.matrix(frame) - Data Frame to Numeric
Matrix
Lists
list(...) - Lists
unlist(x,...) - Flatten Lists
lapply(x, fun, ...), sapply(x, fun, ...) - Apply a Function Over a List
Functions
function(arglist)expr - Function
Definition - invisible(value), return(value)
formals(fun=sys.function(sys.parent())) - Access
to the Formal Arguments
missing(x) - Does a Formal Argument have a Value?
nargs() - The Number of Arguments to a Function
args(fun) - Argument list of a function; fun
- See list of the program
call(name, ...), is.call(expr), as.call(expr)
- Function Calls
do.call(fun, args) - Execute a Function Call
match.call(...) - Argument Matching
invisible(expr) - Change the Print Mode to
Invisible
warning(message) - Warning Messages
on.exit(expr) - Function Exit Code
stop(message) - Stop Function Execution
Expressions
expression(...) - Unevaluated Expressions
all.names(expr, functions=T, max.names=200,
unique=F) - Find all Names in an Expression
all.vars(expr, functions=T, max.names=200,
unique=F) - Find all Names in an Expression
parse(file="", ...) - Parse Expression
deparse(expr, width.cutoff=60)
- Expression Deparsing
quote(arg, ....), substitute(arg, ...) - Actual
Arguments
Environment
environment(fun = NULL), environment(fun) <- value
, is.environment(obj), .GlobalEnv - Environment Access
getenv(x) - Get Environment Variables
exists(x, ...) - Is a Variable Defined ?
get(x, ...) - Return a Variable's Value
eval(expr, ...) - Evaluate an (Unevaluated) Expression
sys.call(), sys.frame(), sys.nframe(), sys.function(),
sys.parent() - Functions to access the function call stack
sys.calls(), sys.frames(), sys.parents(),
sys.on.exit()
Formatting and Printing
format(x, ...), format.default - Encode in a Common
Format
formatC(x, ...) - Flexible Formatting
print(x, ...) - Print Values
print.default(x, ...) - Default Printing
Listing and Loading Libraries
library() - List all available packages
library(name, ...), require(name, ...), provide(name)
- Load specific package
library.dynam(chname), .lib.loc, .Library, .Provided,
RLIBS
names(x), names(x) <- value - The Names Attribute of
an Object
attach(what, ...) - Attach Set of \R Objects to
Search Path
detach(name, ...) - Detach \R objects from search
path
autoload(name, file), .AutoloadEnv - On-demand
loading of packages
Time, Time ... Time
system.date() - Print the System Date and Time
system.time(expr) - CPU Time Used
proc.time() - Running Time of R
Symbolic and Algorithmic Derivatives of Simple Expressions:
D(expr, namevec), deriv(expr, ...), deriv.default(),
deriv.formula()
uniroot(f, interval, ...) - One Dimensional Root
Finding
polyroot(z) - Find Zeros of a Complex Polynomial
optimize(f=, interval=, ...) - One Dimensional
Optimization
nlm(f, p, ...) - non-linear minimization
Single Value Decomposition of a Matrix and Eigenvalues:
svd(x, ...), a generalization of
eigen(x, ...), a Spectral Decomposition of a Matrix
qr(x,...) - The QR Decomposition of a Matrix
qr.coef(), qr.fitted(), qr.qty(), qr.qy(), qr.resid(),
qr.solve
qr.Q(), qr.R(), qr.X() - Reconstruct the Q, R, or X
Matrices from a QR-Object
chol(x) - The Choleski Decomposition
chol2inv(x, ...) - Inverse from Choleski
Decomposition
Geometric: dgeom(x, p), pgeom(q, p), qgeom(prop, p), rgeom(n, p)
Hypergeometric: dhyper(x, N1, N2, n), phyper(q, N1, N2, n), qhyper(p, N1, N2, n), rhyper(nobs, N1, N2, n)
Negative Binomial: dnbinom(x, n, p), pnbinom(q, n, p), qnbinom(prob, n, p), rnbinom(nobs, n, p)
Poisson: dpois(x, lambda), ppois(q, lambda), qpois(p, lambda), rpois(n, lambda)
Chi-Square: dchisq(x, df), pchisq(q, df), qchisq(p, df), rchisq(n, df)
Exponential: dexp(x, rate=1), pexp(q, rate=1), qexp(p, rate=1), rexp(n, rate=1)
F: df(x, n1, n2), pf(q, n1, n2), qf(p, n1, n2), rf(n, n1, n2)
Non-Central Chi-Square: dnchisq(x, df, lambda), pnchisq(q, df, lambda), qnchisq(p, df, lambda), rnchisq(n, df, lambda)
Normal: dnorm(x, mean=0, sd=1), pnorm(q, mean=0, sd=1), qnorm(p, mean=0, sd=1), rnorm(n, mean=0, sd=1)
Student's t: dt(x, df), pt(q, df), qt(p, df), rt(n, df)
Uniform: dunif(x, min=0, max=1), punif(q, min=0, max=1), qunif(p, min=0, max=1), runif(n, min=0, max=1)
Missing Values in Given Data
NA, as.na(x), is.na(x) - Not Available Value;
na.action(x, ...), na.action.default(x)
- NA Action
na.fail(frame), na.omit(frame) - Handle Missing
Values in Data Frames
complete.cases(...) - Find Complete Cases
Univariate Description
Elementary:
all(x), any(x) Are All/Any Values True ?
length(x) of a Vector or List
quantile(x) ;
min(...,), max(...,), pmin(...,), pmax(...,) ;
range(...,) ; median(x)
cumsum(x), cumprod(x), cummin(x), cummax(x)
- Cumulative Sums, Products, Mins, and Maxs
Usual:
sum(...,) ; mean(x) ;
sd(x) - Standard Deviation;
var(x) - Variance
Notice: Least-squares-estimators have to have robust and resistent
accompanies, like the ones below.
Usefull:
pretty(x, n=5) - Pretty Breakpoints
diff(x, lag=1, differences=1) - Lagged Differences
Exploratory:
stem(x) - Stem-and-Leaf Plot;
fivenum(x) - Tukey Five-Number Summary;
median(x) - Cut Data at 50%;
weighted.mean(x, w) - Weighted Arithmetic
Mean;
IQR(x) - Interquartile Range;
mad(x, center) - Median Absolute Deviation
symnum(x, ...) - Symbolic Number Coding
Bi- and Multivariate Description
table(...) - Cross Tabulation of categorial, nominal,
or level Data - Contingency Tables;
tabulate(bin, nbin=max(bin)) - Tabulation for
Vectors
cut(x, breaks, ...) - Convert Numeric to Factor
split(x, f) - Divide Values of x into Groups defined
by Factor f;
var(x, y) , cov(x, y) ,
cor(x, y) - Covariance and Correlation Matrices
symnum(x, ...) - Symbolic Number Coding
Elementary Statistical Tests
prop.test(x, n, ...) - Test for Equal or Given
Proportions;
chisq.test(x, ...) - Pearson's Chi-square Test
for Count Data;
t.test(x, ...) - Student's t-Test
Statistical Modelling and Evaluation
Least Squares Regression
lsfit(x, y, wt, ...) - Find the Least Squares Fit -
lm should usually be preferred (see below)
Resistance and Robustness of Least-Squares-Estimates must be controlled !
ls.diag(ls.out) - Compute Diagnostics for 'lsfit'
Results
ls.print(ls.out, ...) - Print 'lsfit' Regression
Results
Time Series
Objects:
ts(...), as.ts(x), is.ts(x), print.ts(), plot.ts()
Sampling Times of Time-Series:
time(x, ...), start(x), end(x), frequency(x), tsp(x)
window(x, start, end) - Time Windows
Discrete Fourier Transform:
fft(z, ...), mvfft(z, ...)
convolve(a, b)
nextn(n, ...)
Kernel Density Estimation:
density(x, ...), bw.bcv(x, ...), bw.sj(x, ...),
bw.ucv(x, ...)
plot.density(dobj, ...) print.density(dobj)
Set, Query, or View Colors
colors(), colours() - Color Names;
palette(value) - Set or View the Graphics Palette
rainbow(n,...), heat.colors(n), terrain.colors(n),
topo.colors(n)
Kinds of Specification:
gray(level) ,
hsv(hue, saturation, value)
rgb(red, green, blue)
Set or Query Parameters
frame() - Start a New Plot Frame
par(...) - Handle Manifolds of Design-Attributes;
par(mfrow=c(nrows, ncols)) - Sets nrows*ncols Plots
per Page,
par(mfrow=c(1,1)) - Resets to one Plot per Page
xinch(x=1), yinch(x=1) - Graphical Units
Plot and Add Graphical Elements
plot(x, y, ...) - X-Y Plotting
plot.default(x,...) - The Default Scatterplot
Function;
plot.xy(xy, type,...) - Basic Internal Plotting
Function
xy.coords(x, y,...) - Extracting Plotting
Structures
curve(expr, from, to, ...) - Draw Function Plots
points(x,...), points.default(x,...) - Add Points to
a Plot
lines(x,...), lines.default(x,...) - Add Connected
Line Segments to a Plot
abline(...) - Add a Straight Line to a Plot
grid(nx=, ny=, ...) - Add Grid to a Plot
box(...) - Draw a Box around a Plot
rect(xleft, ybottom, xright, ytop, ...) - Draw a
Rectangle
polygon(x, y,...) - Polygon Drawing
title(...) - Plot Annotation
text(x,...) - Add Text to a Plot
strheight(s, ...), strwidth(s, ...) - Plotting
Dimensions of Character Strings and Math Expressions
mtext(text,...) - Write Text into the Margin of a Plot
arrows(x0, y0, x1, y1,...), segments(x0, y0, x1, y1,...)
- Add Arrows or Segments to a Plot
axis(which, at,...) - Add an Axis to a Plot
legend(x, y, legend, fill,...) - Add Legends to Plots
One-Dimension Plots
piechart(x, ...) - Pie Charts; a very bad way of
displaying information
hist(x, ...) - Histograms;
barplot(height, ...) - Bar Plots;
dotplot(x, ...) - Cleveland Dot Plots
boxplot(..., ...) - Box Plots
boxplot.stats(x, ...) - Box Plot Statistics;
bxp(z, width, ...) - Box Plots from Summaries
stripplot(x, ...) - 1-D Scatter Plots
qqnorm(y, ylim, ...), qqline(y, ...), qqplot(x, y, ...)
Quantile-Quantile Plots
ppoints(n) - Ordinates for Probability Plotting
Two-Dimension Plots
lowess(x, y, ...) - Scatter Plot Smoothing
approx(x, y, xout, ...), approxfun(x, y, ...)
- Interpolation Functions
spline(x, y, ...), splinefun(x, y, ...)
- Interpolating Splines
identify(x, ...) - Identify Points in a Scatter
Plot
pairs(x, ...) - Scatterplot Matrices
matplot(x, y, ...), matpoints(x, y, ...),
matlines(x, y, ...) - Plot Columns of Matrices
coplot(formula, data, given.values, ...),
co.intervals(x, ...) - Conditioning Plots
Three-Dimension Plots
image(x, y, z, zlim, ...) - Display a color image
rainbow(n,...), heat.colors(n), terrain.colors(n),
topo.colors(n)
Kinds of Specification:
gray(level) ,
hsv(hue, saturation, value)
rgb(red, green, blue)
contour(x=, y=, z, ...) - Display Contours, e.g.
demo(graphics), or demo(image)
Graphical Input
locator(n=1) - Do you want to believe ?-)
call(name, ...), is.call(expr), as.call(expr)
- Function Calls
do.call(fun, args) - Execute a Function Call
match.call(...) - Argument Matching
invisible(expr) - Change the Print Mode to
Invisible
warning(message) - Warning Messages
on.exit(expr) - Function Exit Code
stop(message) - Stop Function Execution
assign("object", expr) - General assignment function
Control Flow
if(cond) expr
if(cond) cons.expr
else alt.expr
for(var in seq)
expr
while(cond) expr
repeat expr
break
next
ifelse(test, yes, no) - Conditional Element Selection
switch(expr, ...) - Select One of a List of Alternatives
Interaction with the User
interactive() - Is \R running interactively ?
menu(x) - Menu Interaction Function
readline() - Read a Line from the Terminal
cat(... ,) - Concatenate and Print
Listing and Loading Libraries
library() - List all available packages
library(name, ...), require(name, ...), provide(name)
- Load specific package
library.dynam(chname), .lib.loc, .Library, .Provided,
RLIBS
names(x), names(x) <- value - The Names Attribute of
an Object
attach(what, ...) - Attach Set of \R Objects to
Search Path
detach(name, ...) - Detach \R objects from search
path
autoload(name, file), .AutoloadEnv - On-demand
loading of packages
Foreign Function Interface
.C(name,...), .Fortran(name,...) ,
dyn.load(libname), symbol.C(name), symbol.For(name)
.Internal(call) - Call an Internal Function -
For true Wizards only
Tracing and Debugging
trace(fun), untrace(fun) - Trace all calls to a
function;
traceback - Print Call Stack of Last Error
debug(fun), undebug(fun) - Debug a function
browser() - Environment Browser
Time, Time ... Time
system.date() - Print the System Date and Time
system.time(expr) - CPU Time Used
proc.time() - Running Time of R
Prepare Publication
prompt(object,...), prompt.default(object,...)
- Produce Prototype of an R\ Documentation File
To Close the Circle: help
BROWN, B.W.: S Cheatsheet.
http://lib.stat.cmu.edu/S/cheatsheet
CARROLL, J.M.: Human-Computer-Interaction: Psychology as a Science of Design.
In: SPENCE, J.T., DARLEY, J.M. & FOSS, D.J.(Ed): Annual Review of
Psychology. Vol. 48, 1997, p.61-83.
KRAUSE, A. & OLSON, M.: The Basics of S and S-PLUS. New York: Springer, 1997.
R: R Function Index: base, e.g.
http://stat.ethz.ch/R-alpha/doc/html , Version 0.61.2 (from R for m68k),
May 1998.
StatSci: Roadmap to S-PLUS for Windows. Seattle: Statistical sciences. Inc.,
1993.
VENABLES, B., SMITH, D., GENTLEMAN, R. & IHAKA, R.: Notes on R: A Programming
Environment for Data Analysis and Graphics.
http://www.ci.tuwien.ac.at/R/doc/Rnotes.ps.gz , 1997.
VENABLES, W.N. & RIPLEY, B.D.: Modern Applied Statistics with S-PLUS. New York:
Springer, 1997.
Improvements qua suggestions from: Carsten Drücke, Stephan Noller
Critics and hints on contents and design are welcome:
Hartmut
Oldenbürger
last: December 16, 1998.