[up]

R Cheatsheet: base - Overview

Userability = Content + Top-Down + Completeness + Redundancy: Viewing from the User-Perspective.
Acknowledgements - This is a preliminary sketch for R-0.61.2, under GPL.
Study the many fine examples given by the referenced pages.
And: See the source of a function, just by entering its name (without brackets ;-).

For full use of this overview, you should have read a document like VENABLES, SMITH, GENTLEMEN & IHAKA, 1997 .
[top] [next] [bot]

Contents

Join and Leave R - Orientation

R Expressions - Operators - Arithmetic Functions

In and Out of R - Handling Data Types, Objects, and more

MuchMore Handling
General Object | Classes and Methods | Vectors | Matrices | Arrays | Frames | Lists | Functions | Expressions | Environment | Formatting and Printing | Listing and Loading Libraries | Time, Time ... Time

Mathematical Diversions - Theoretical Statistical Distributions

Data Analysis and Statistics
Creating Data Randomly | Missing Values in Given Data | Univariate Description | Bi- and Multivariate Description | Elementary Statistical Tests | Statistical Modelling and Evaluation | Time Series

Graphics
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

Programming
Functions | Control Flow | Interaction with the User | Listing and Loading Libraries | Foreign Function Interface | Tracing and Debugging | Time, Time ... Time | Prepare Publication

References


[top] [back] [next] [bot]

Join and Leave R

Unix: Before you invoke the R-System, enter 'man R', and study it carefully!
- To start it, change to your Work-Directory, and enter 'R'.

WindowsXX: Click, click ...

quit(), q() - Terminate an R-Session.


[top] [back] [next] [bot]

Orientation

demo() - List available running demos of R-Scripts; demo(topic) - Run specific demo

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 ;-)


[top] [back] [next] [bot]

R Expressions

Literals

numerics - E.g.: 1, 1.1, 1.1e10
character strings - E.g.: 'string' or "string"
logicals - T, TRUE, F, FALSE
# comments - # R language comments

Calls

expr operator expr - E.g.: 2*8, 2^8, x %/% y
unary expr - E.g.: -5, !logical
function ( arglist ) - E.g.: sqrt(256), plot(x,y)

Assignments

object <- expr - Assigns expr to object with legal names
expr -> object - Alternate assignment form
assign("object", expr) - General assignment function
object <<- expr - Assign to working directory from within a function

Built-In Constants: LETTERS, letters, month.abb, month.name, pi

Extract or Replace Parts of an Object

expr [ arglist ] - E.g.: x[3], x[x>3], mylist[1:3]
list[[ arglist ]] - Select a single component, e.g. mylist[[2]]
list$formal.name - Select named component from list, e.g. 'mylist$stuff', same as 'mylist[["stuff"]]'

Remove Objects

remove(...,), rm(...,) - Remove Objects from a Specified Environment


[top] [back] [next] [bot]

Operators

Arithmetic:
x + y - addition; x - y - subtraction; x * y - multiplication; x / y - division; x ^ y - exponentiation
x %% y - x mod y; x %/% y - integer division

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


[top] [back] [next] [bot]

Arithmetic Functions

Rounding of Numbers: ceiling(x) ; floor(x) ; round(x, digits=0) ; signif(x, digits) ; trunc(x)

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.


[top] [back] [next] [bot]

In and Out of R

Invoke external Editor

General: edit(name=NULL, file="", editor="vi")
Special Ones: vi(), emacs(), xemacs(), xedit()

fix(x) - Fix an Object

Spreadsheet Interface for Entering Data

data.entry(...,), dataentry(data, modes)
de(...,), de.ncols(), de.restore(), de.setup() - help achieve side effects

Read Data by the System

scan() - read data values from file or keyboard
read.table() - principal means of reading tabular data from file into R
count.fields(file, sep="", skip=0) - Count the Number of Fields per Line

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

Write and Read Objects

dput(x, file="") - opens file and deparses the object x into that file
dget(file) - recreates the object

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 ;-)


[top] [back] [next] [bot]

Handling Data Types, Objects, and more

What it is Create Force Test See also, and more
Multi-Way Arrays array(x, dim=dim) as.array(x) is.array(x) aperm() , matrix()
Atomic Objects is.atomic(x)
Function Calls call(name, ...) as.call(expr) is.call(expr) expression(), function()
Character String Vectors character(n=0) as.character(x) is.character(x)
Complex Vectors complex() as.complex(x) is.complex(x) Re(z), Im(z), Mod(z), Arg(z), Conj(z)
Data Frames data.frame(...) as.data.frame(x) is.data.frame(x) row.names(data.frame.obj), print(...)
Double Precision Vectors double(n=0) as.double(x) is.double(x) integer()
Environment Access environment() is.environment(obj) .GlobalEnv, eval()
Unevaluated Expressions expression(...) as.expression(expr) is.expression(expr) call(), eval(), function()
Factors factor(x, ...) as.factor(x) is.factor(x) gl() levels(), nlevels(), codes()
ordered(x, ...) as.ordered(x) is.ordered(x)
is.unordered(x)
Finite Elements is.finite(x) finite
Function Type function(arglist)expr is.function(x)
Integer Vectors integer(n=0) as.integer(x) is.integer(x)
Language Object is.language(x)
Lists list(...) as.list(x) is.list(x) vector()
Foreign Function Interface dyn.load(libname) is.loaded(symbol) symbol.C(name) symbol.For(name)
Logical Vectors logical(n=0) as.logical(x) is.logical(x)
Create a Matrix matrix(, nrow, ncol) as.matrix(x) is.matrix(x)
Not Available Value NA as.na(x) is.na(x) complete.cases()
Variable Names name(string) as.name(x) is.name(x)
NULL Object NULL as.null(x) is.null(x)
Numeric Vectors numeric(n=0) as.numeric(x) is.numeric(x) All real numbers are double precision.
QR Decomposition qr(x, ...) as.qr(x) is.qr(x)
Recursive Object is.recursive(x)
Real Vectors real(n=0) as.real(x) is.real(x) All real numbers are double precision.
Single Precision Type is.single(x) Single precision doesn't exist in R
Time-Series Objects ts(...) as.ts(x) is.ts(x) print.ts(), plot.ts()
Vector Types vector(...) as.vector(x, ...) is.vector(x)


[top] [back] [next] [bot]

MuchMore Handling

General Object

attr(obj, which), attr(obj, which) <- value - Object Attributes
attributes(obj), attributes(obj) <- list - Object Attribute List
structure(data, ...) - Attribute Specification
typeof(x) - The Type of an Object
mode(x), mode <- "<mode>", storage.mode(x), storage.mode <- "<mode>" - The (Storage) Mode of an Object

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

Complex Values

Re(z) - real part; Im(z) - imaginary part; Mod(z) - modulus; Arg(z) - argument; Conj(z) - complex conjugate;

Strings

character(n=0) - Character String Vectors; nchar(x) - Count The Number of Characters
pmatch(x, table, ...) - Partial String Matching - charmatch(x, table, ...)
match.arg(arg), match(arg, choices) - Argument Verification Using Partial Matching
substr(x, start, stop) - Extract Substrings from a Character Vector -substring(x, start, stop)
Pattern Matching and Replacement:
grep(pattern, x, ...), sub(pattern, replacement, x, ...), gsub(pattern, replacement, x, ...)
abbreviate(names.arg, ...) - Abbreviate Strings
paste(...) - Concatenate Strings
strsplit(x, split) - Split the Strings in a Vector

[.noquote, noquote(obj), print.noquote(obj, ...) - Class for "no quote" Printing of Strings

Position of Components

rev(x) - Reverse a Vector`s Elements

order(...) - Ordering Permutation; aperm(a, perm, ...) - Array Transposition
sort(x,...) - Sort a Vector
rank(x) - Sample Ranks

Contents of Components

unique(x) - Extract Unique Elements
duplicated(x) - Determine Duplicate Elements
Data-analytic Functions: Univariate Description

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
delay(expr) - Delay Evaluation

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


[top] [back] [next] [bot]

Mathematical Diversions

solve(a, b,...) - Solve a System of Equations
backsolve(r, x,...) - Solve an Upper Triangular System

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


[top] [back] [next] [bot]

Theoretical Statistical Distributions

d<dist>(x,<parameters>) - Distribution function; density at x
p<dist>(q,<parameters>) - Probability function; cumulated density to x
q<dist>(p,<parameters>) - Quantile function; inverse of the probability function
r<dist>(n,<parameters>) - Random number generation for specified distribution

Discrete:

Binomial: dbinom(x, n, p), pbinom(q, n, p), qbinom(prop, n, p), rbinom(nobs, n, p)

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)

Continuos:

Beta: dbeta(x, a, b), pbeta(q, a, b), qbeta(p, a, b), rbeta(n, a, b)

Cauchy: dcauchy(x, location=0, scale=1), pcauchy(q, location=0, scale=1), qcauchy(p, location=0, scale=1), rcauchy(n, location=0, scale=1)

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)

Gamma: dgamma(x, shape, scale=1), pgamma(q, shape, scale=1), qgamma(p, shape, scale=1), rgamma(n, shape, scale=1)

Logistic: dlogis(x, location, scale=1), plogis(q, location. scale=1), qlogis(p, location, scale=1), rlogis(n, location, scale=1)

Log Normal: dlnorm(x, meanlog=0, sdlog=1), plnorm(q, meanlog=0, sdlog=1), qlnorm(p, meanlog=0, sdlog=1), rlnorm(n, meanlog=0, sdlog=1)

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)

Weibull: dweibull(x, shape, scale=1), pweibull(q, shape, scale=1), qweibull(p, shape, scale=1), rweibull(n, shape, scale=1)


[top] [back] [next] [bot]

Data Analysis and Statistics

Creating Data Randomly

Offspring:
.Random.seed - Random Number Generation
Sampling from Theoretical Statistical Distributions: See all these r.....-Functions just above
Resampling from Given Data - Randomization and Bootstrapping:
sample(x, size, ...) - Random Samples and Permutations

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

Design: Factors, Levels, and Codes

gl - Generate Factor Levels
factor(x, ...), as.factor(x), is.factor(x), ordered(x, ...), as.ordered(x), is.ordered(x) - Factors
tabulate(bin, nbin=max(bin)) - Tabulation for Vectors
levels(x), levels(x) <- - Level Names for a Factor
nlevels(x) - The Number of Levels of a Factor
codes(x), codes(x) <- - Factor Codes

Model-Syntax

~ ; - Model Formulae ; formula.default(), formula.formula(), formula.terms(), print.formula()
terms ; - Model Terms ; terms.default(), terms.formula(), terms.terms(), print.terms()
model.frame(formula, data, na.action, ...), model.frame.default(formula, ...)
- Extracting the "Environment" of a Model Formula
model.matrix(formula=, data= ) - Construct Design Matrices
update.model(old, new) - Model Updating

Linear Models: Regression, Single Analysis of Variance and Covariance

lm(formula, data, subset, weights) - Fitting creates lm.obj
anova(lm.obj) - Analysis-of-Variance-Table; summary(lm.obj) - Object Summaries
Generic accessor functions: coefficients(lm.obj), deviance(lm.obj), df.residual(lm.obj),
effects(lm.obj), fitted.values(lm.obj), predict(lm.obj), residuals(lm.obj)
; update.lm ; weights(lm.obj)
Regression Diagnostics: lm.influence(lm.obj) , influence.measures(lm.obj),
rstudent(lm.obj), dfbetas(lm.obj), dffits(lm.obj), covratio(lm.obj), cooks.distance(lm.obj), hat(xmat)

lm.fit(x, y), lm.wfit(x, y, w)
Out: print.lm ; print.anova.lm(), print.summary.lm()

Contrasts

contrasts(x) - Get and Set Contrast Matrices
contr.helmert(n, ...), contr.poly(n, ...), contr.sum(n, ...), contr.treatment(n, ...) - Contrast Matrices

Generalized Linear Models

glm(formula, family=..., data, weights, subset, ...) - Fitting creates glm.obj
Error Distribution: family(object), binomial(), Gamma(), gaussian(), inverse.gaussian(), poisson(), quasi()
anova(glm.obj,...) - Analysis-of-Variance-Table; summary(glm.obj,...) - Object Summaries
Generic accessor functions: coefficients(glm.obj) ; deviance(glm.obj), df.residual(glm.obj), effects(glm.obj) ;
family(glm.obj), fitted.values(glm.obj), residuals(glm.obj, ...)
; update.glm
glm.control(...), glm.fit(x, y, ...)
Out: print.glm(), print.anova.glm(), print.summary.glm()

Generic Functions for Models

anova(object, ...) - Anova Tables; coef(x, ...), coefficients(x, ...) - Extract Model Coefficients;
fitted(x, ...), fitted.values(x, ...) - Extract Model Fitted Values; predict(object, ...) - Model Predictions;
deviance(x, ...) - Model Deviance; df.residual(x, ...) - Residual Degrees-of-Freedom;
resid(x, ...), residuals(x, ...) - Extract Model Residuals;
summary(object, ...) - Object Summaries

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)


[top] [back] [next] [bot]

Graphics

Devices

ps.options(), ps.options(paper, horizontal, width, height, family, pointsize, bg, fg)
- View and Set Values for the Arguments of PostScript graphics
postscript(...) - Writes PostScript graphics commands into file
pictex(...) - Writes LaTeX/PicTeX graphics commands into file
x11(...) - The graphics driver for the X11 Window system (Unix), print.plot(), save.plot(file)
windows(...) - The graphics driver for MS Windows
macintosh(...) - The graphics driver for the Macintosh
dev.off(), graphics.off() - Turn off all Graphics Devices

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 ?-)


[top] [back] [bot]

Programming

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

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


[top] [back]

References

The compilation of this document benefitted from:

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.