Show Menu
Cheatography

R Cheat Sheet (DRAFT) by [deleted]

R Language

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

General

Get Help
? <Ob­jec­t/F­unc­tio­n>
Find the working directory
getwd()
Setting Working directroy
setwd(­"­~/s­pec­dat­a")
List files in working dir
dir()
Load code file into workspace
source­("fi­le.R­")
Find the type of an object
class(­my_­vector)
List objects in workspace
ls()
Change page width
option­s(width = 160)

Operators

Assign­ement
var <- <New value>
Compare two objects
identical( obj1, obj2 )
Equality
var1 == var2

Special Values

NA
value is Not Available
NaN
Not a Number
Inf
Infinity
T
True
F
False

Subsetting Vectors

First 10 elements
x[1:10]
Vector of all NAs
x[is.n­a(x)]
Vector of real values
x[!is.n­a(x)]
Values greater than 0
y[y > 0]
Combine conditions
x[!is.n­a(x) & x > 0]
3rd, 5th, 7th elements of x
x[c(3,­5,7)]
All but the 2nd and 10th (neg)
x[c(-2, -10)] or x[-c(2­,10)]
Access element by label
vect["b­ar"] or vect[c­("fo­o", "­bar­")]
Index vectors come in four different flavors -- logical vectors, vectors of positive integers, vectors of negative integers, and vectors of character strings

Debugging

traceback
Prints function call stack
debug( <fn> )
Flags a function for "­deb­ug" mofr which allows you to step through execution of a function one line at a time
browser
Suspends the execution of a function, and outs the function in debug mode. n- next
trace
Allows you to insert debugging code into a function
recover
Allows you to modify the error behaviour so that you can browse the function call statck
 

Vectors

Concat­inate function
patients <- c("B­ill­"­,"Gi­na",­"­Kel­ly",­"­Sea­n")

Matrices

Help on matrix type
? matrix
Add dimensions to vector to make a matrix
dim(my­_ve­ctor) <- c(4, 5)
View dimesions of a matrix
dim(my­_ma­trix)
View dimesions of a matrix
attrib­ute­s(m­y_m­atrix)
Create a matrix. ( 4x5 containing 1-> 20)
my_matrix2 <- matrix( 1:20,4,5 )
+ Matrices can only contain a single class of data.
+ The first number is the number of rows and the second is the number of columns.

Data Frames

Create a data frame from avector and matrix
my_data <- data.f­ram­e(p­ati­ents, my_matrix)
Add columns name to data frame
colnam­es(­my_­data) <- cnames­_vector
Select rows based on column value
frame[ frame$col == "­val­", ]
Select columns by position
frame[, 1:4]
cols 1 to 4

Conversion

To number
as.num­ber(x)
To boolean (logical)
as.log­ical(x)
To comples number
as.com­plex()

Reading Data

  # Create empty data frame
  data <- data.frame()
  
  #Readfiles id is vector of integers
  for ( i in id ){
    infile = sprintf("%s/%03d.csv", directory, i)
    data <- rbind(data,read.csv( infile ))
  }
  head(data)
 

IF statement

if(<condition>) {
    ## do something
} else {
    ## do something else
}

if(<condition1>) {
    ## do something
} else if(<condition2>) {
    ## do something different
} else {
    ## do something different
}

For Statement

for(i in 1:10) {
    print(i)
}

While Statem­ement

count <- 0
while(count < 10) {
    print(count)
    count <- count + 1
}

Repeat Statement

x0 <- 1
tol <- 1e-8
repeat {
    x1 <- computeEstimate()
    if(abs(x1 - x0) < tol) {
        break
    } else {
        x0 <- x1
    }
}

next,r­eturn

for(i in 1:100) {
    if(i <= 20) {
        ## Skip the first 20 iterations
        next
    }
    ## Do something here
}
next is used to skip an iteration of a loop

Loop functions

lapply
Loop over a list and evaluate a function on each element
sapply
Same as lapply but try to simplify the result
tapply
Apply a function over the margins of an array
mapply
Multiv­ariate version of lapply
apply
Used to evaluate a function ( often an anonymous one ) over the margins of an array.
rowSums
apply(­x,1­,sum)
rowMeans
apply(­x,1­,mean)
colSums
apply(­x,2­,sum)
colMeans
apply(­x,2­,mean)
x<- list( a = 1:5, b= rnorm(10))

lapply­(x,­mean)


An annonymous fn for extracting the 1st col of each matrix
>la­ppl­y(x­,fu­nct­ion­(elt) elt[,1])