Show Menu
Cheatography

R Commands Cheat Sheet (DRAFT) by

Basic R commands used in a lecture on statistical programming.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Basic Math

exp(x)
Expone­ntial
sum(x)
Sum
log(x)
Natural log
cumsum(x)
Cumulative Sum
max(x)
Largest element
ceil(x)
Round up
min(x)
Smallest element
floor(x)
Round down
mean(x)
Mean
median(x)
Median
var(x)
Variance
quanti­le(x)
Percentage quantiles
x %% y
Modulo

I/O

write(­data, "­myd­ata.da­t")
Write data as binary.
scan("m­yda­ta.d­at­")
Read binary data.

Plotting

plot(data)
Plot quick overview.
barplot(x, main="T­itl­e", xlab="x label")
Annotated barplot of absolute freque­ncies
plot.e­cdf­(data)
Plot ECDF.
hist(data, prob=TRUE, breaks=30)
Histogram of relative freque­ncies (30 bins).
rug(data)
1D-plot
abline­(a,­b,c­ol=­"­red­")
Add a red line with intercept
a
and slope
b
to the plot.

Vectors

Creating Vectors
c(2, 4, 6)
Join elements into a vector
2:6
An integer sequence (end inclus­ive!)
seq(2,3, by=0.5)
Complex sequence (s. np.lin­space)
rep(1:2, 3)
Repeat vector
rep(1:2, 3:4)
Repeat each element
Functions
sort(x)
Return x sorted.
rev(x)
Return x reversed.
unique(x)
See unique values.
length(x)
Length of x.
Tables
table(x)
Generate absolute frequency table
as.num­eri­c(n­ame­s(t­ab)); as.vec­tor­(tab)
Access values and freque­ncies of the table
Selecting Vector Elements
By Position
x[4]
The fourth element
x[-4]
All but the fourth.
x[2:4]
Elements two to four
x[-(2:4)]
All elements except 2 to four
x[c(1, 5)]
Elements one and five.
By Value
x[x == 10]
All elements equal to 10
x[x  < 10]
All elements less than 10.
x[x %in% c(1, 2, 5)]
Elements in the given set.
Named Vectors
x['apple']
Element with name 'apple'.

Control Flow

for (variable in sequence) {...}
for-loop. If the loop body contains only a single line, the curly brackets can be omitted.
while (condi­tion) {...}
while-loop
if (i > 5) {

  ...

else {

  ...

}
if-els­e-block
foo = functi­on(­arg1, arg2, ...) {

  ...

  return­(var)

}
function

Runs Test of Randomness

rle(x)
Compute the lengths and values of runs of equal values in a vector .
rle(x)­$le­ngths
Vector containing the length of each run.
rle(x)­$values
Vector of the same length as lengths with the corres­ponding values.

Help

?sqrt
Display docume­ntation of the command
sqrt
`
?'%%'
use quotation marks for special characters

Miscel­laneous

Printing
print(­"­Tex­t")
Default print
sprint­f("F­orm­atted %s: %.3f", object, mean)
Formatted print
(x=3)
enclose an R command with brackets to directly print the result

Random Numbers

sample­(1:­3,p­rob­=c(­1/6­,1/­3,1­/2)­,re­pla­ce=­TRU­E,20)
Draw 20 balls, labeled from 1 to 3, from box with replac­ement.
r<d­istr. ID>
(n, params)
Draw
n
numbers from distri­bution
<distr. ID>
with parameters
params