Show Menu
Cheatography

R essentials Cheat Sheet (DRAFT) by

Essentials of R programming

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

R help functions

help.s­tart()
General help
help(plot) or ?plot
Help on function
plot
help.s­ear­ch(­"­geo­")
Search help system for instances of string geo
exampl­e(plot)
Examples of function
plot
RSiteS­ear­ch(­"­geo­")
Search for string geo in online help manuals and archived mailing lists
apropo­s("g­eo", mode="f­unc­tio­n")
List all available functions with geo in their name
data()
List all example datasets in loaded packages
vignette()
List all vignettes for installed packages
vignet­te(­"­geo­")
Display specific vignettes for topic geo

Managing R workspace

getwd()
Get working directory
setwd(­"­myd­ire­cto­ry")
Set working directory to mydire­ctory
ls()
List the objects in workspace
rm(obj­ect­list)
Remove one or more objects
help(o­ptions)
Learn about available options
options()
View or set current options
history(#)
Display the last # of commands (defau­lt=25)
savehi­sto­ry(­"­myf­ile­")
Save the commands history to myfile (default = .Rhistory)
loadhi­sto­ry(­"­myf­ile­")
Reload a commands history (default = .Rhistory)
save.i­mag­e("m­yfi­le")
Save the workspace to myfile (default = .RData)
save(o­bje­ctlist, file = "­myf­ile­")
Save specific objects to a file
load("m­yfi­le")
Load a workspace in the current session (default = .RData)
q()
Quit R. Will be prompted to save the workspace.
setwd(­"­C:/­myp­roj­ect­s/p­roj­ect­1")

options()

option­s(d­igi­ts=3)

x <- runif(20)

summary(x)

hist(x)

savehi­story()

save.i­mage()

q()
 

Saving graphic output

pdf("fi­len­ame.pd­f")
PDF file
win.me­taf­ile­("fi­len­ame.wm­f")
Windows metafile
png("fi­len­ame.pn­g")
PBG file
jpeg("f­ile­nam­e.j­pg")
JPEG file
bmp("fi­len­ame.bm­p")
BMP file
postsc­rip­t("f­ile­nam­e.p­s")
PostScript file
jpeg("r­plo­t.j­peg­")

plot(x,y)

dev.off()

Packages

.libPa­ths()
Shows where library is located
library()
Shows the packages saved in the library
search()
Shows which packages have been loaded and ready to use
instal­l.p­ack­age­s("g­gpl­ot")
Install a package for the first time
update.pa­cka­ges­("gg­plo­t")
Update packages that have been installed
instal­led.pa­cka­ges()
Lists packages with version numbers, depend­encies, and other info
librar­y(g­gplot)
Load package
help(p­ack­age­="gg­plo­t")
Brief descri­ption of package and index of functions and datasets
help.s­tart()

instal­l.p­ack­age­s("v­cd")

help(p­ack­age­="vc­d")

librar­y(vcd)

help(A­rth­ritis)

Arthritis

exampl­e(A­rth­ritis)

q()

Data input

Keyboard input
mydata <- data.f­ram­e(a­ge=­num­eri­c(0­),g­end­er=­cha­rac­ter­(0)­,we­igh­t=n­ume­ric(0))
 
mydata <- edit(m­ydata)
or
fix(my­data)
Delimited text file
mydata­frame <- read.t­abl­e("f­ile­", header­=lo­gic­al_­value, sep="de­lim­ite­r",r­ow.n­am­es=­"­nam­e",s­tri­ngs­AsF­act­ors­=lo­gic­al_­value)
Excel file
librar­y(R­ODBC)
 
channel <- odbcCo­nne­ctE­xce­l("m­yfi­le.x­ls­")
 
mydata­frame <- sqlFet­ch(­cha­nnel, "­mys­hee­t")
 
odbcCl­ose­(ch­annel)
or
 
librar­y(xlsx)
 
workbook <- "­c:/­myw­ork­boo­k.x­lsx­"
 
mydata­frame <- read.x­lsx­(wo­rkb­ook,1)
Others
XML, Webscr­apping, SPSS, SAS, Stata, netCDF, HDF5, DBMSs

Accessing DBMSs - RODBC package

odbcCo­nne­ct(dsn, uid=" ", pwd=" ")
Open a connection to an ODBC database
sqlFet­ch(­cha­nnel, sqltable)
Read a table from an ODBC database into a dataframe
sqlQue­ry(­cha­nnel, query)
Submit a query to an ODBC database and return the results
sqlSav­e(c­hannel, mydf, tablen­ame­=sq­table, append­=FALSE)
Write or update (appen­d=TRUE) a data frame to a table in the ODBC database
sqlDro­p(c­hannel, sqtable)
Remove a table from the ODBC database
close(­cha­nnel)
Close the connection
librar­y(R­ODBC)

myconn <- odbcCo­nne­ct(­"­myd­sn", uid="Ro­b", pwd="aa­rdv­ark­")

crimedat <- sqlFet­ch(­myconn, Crime)

pundat <- sqlQue­ry(­myconn, "­select * from Punish­men­t")

close(­myconn)
 

Data structures

Vectors
Hold numeric, character, or logical data e.g.
c(1,2,­3,4,5)
,
c("o­ne",­"­two­"­,"th­ree­")
,
c(TRUE­,TR­UE,­FAL­SE,­FALSE)
Matrices
2D array where each element has the same mode
 
mymatrix <- matrix­(ve­ctor, nrow=n­umb­er_­of_­rows, ncol=n­umb­er_­of_­col­umns, byrow=­log­ica­l_v­alue, dimnam­es=­lis­t(c­har­_ve­cto­r_r­own­ames, char_v­ect­or_­col­names))
Arrays
Similar to matrices but can have more than 2 dimensions
 
myarray <- array(­vector, dimens­ions, dimnames)
Data frames
Different columns can contain different modes of data
 
mydata <- data.f­ram­e(col1, col2, col3, ...)
Factors
Nominal, ordinal or continuous
 
status <- c("P­oor­", "­Imp­rov­ed", "­Exc­ell­ent­", "­Poo­r")
 
status <- factor­(st­atus, order=­TRUE, levels­=c(­"­Poo­r","I­mpr­ove­d","E­xce­lle­nt"))
Lists
Ordered collection of objects
 
mylist <- list(n­ame­1=o­bject1, name2=­obj­ect2, ...)

Example code

cells <- c(1,26,24,68)
rnames <- c("R1","R2")
cnames <- c("C1","C2")
mymatrix <- matrix(cells, nrow=2, ncol=2, byrow=TRUE, dimnames=list(rnames,cnames))

dim1 <- c("A1","A2")
dim2 <- c("B1","B2","B3")
dim3 <- c("C1","C2","C3","C4")
z <- array(1:24, c(2,3,4), dimnames=list(dim1, dim2, dim3))

patientID <- c(1,2,3,4)
age <- c(25,34,28,52)
diabetes <- c("Type1","Type2","Type1","Type1")
status <- c("Poor","Improved","Excellent","Poor")
patientdata <- data.frame(patientID, age, diabetes, status)
patientdata[1:2]
patientdata[c("diabetes","status")]
patientdata$age
# cross tabulate diabetes by status
table(patientdata$diabetes, patientdata$status) 

g <- "My First List"
h <- c(25,26,18,39)
j <- matrix(1:10, nrow=5)
k <- c("one","two","three")
mylist <- list(title=g, ages=h, j, k)
mylist[[2]]
mylist[["ages"]]

Useful tips

Attach, Detach and With
attach (mtcars)

summar­y(mpg)

plot(m­pg,wt)

detach­(mt­cars)


with(m­tcars, {

summar­y(m­pg,­dis­p,wt)

plot(m­pg,­disp)

plot(m­pg,wt)

})


with(m­tcars, {

nokeep­stats <- summar­y(mpg)

keepstats <<- summar­y(mpg)

})

nokeep­stats # object not found

keepstats # object exists in global env with supera­ssi­gnment '<<-'
 

Useful functions

length­(ob­ject)
Number of elemen­ts/­com­ponents
dim(ob­ject)
Dimensions of an object
str(ob­ject)
Structure of an object
class(­object)
Class or type of an object
mode(o­bject)
How an object is stored
names(­object)
Names of components in an object
cbind(­object, object, ...)
Combines objects as columns
rbind(­object, object, ...)
Combines objects as rows
head(o­bject)
Lists the first part of the object
tail(o­bject)
Lists the last part of the object
rm(object, object, ...)
Deletes one or more objects.
rm(lis­t=ls())
will remove most objects.
newobject <- edit(o­bject)
Edits object and saves as newobject
fix(ob­ject)
Edits in place
set.seed()
To have reprod­ucible results

Arithmetic operators

+
Addition
-
Subtra­ction
*
Multip­lic­ation
/
Division
^
or
**
Expone­nti­ation
x%%y
Modulus (x mod y)
x%/%y
Integer division

Logical operators

<
Less than
<=
Less than or equal to
>
Greater than
>=
Greater than or equal to
==
Exactly equal to
!=
Not equal to
!x
Not
x
x | y
x
or
y
x & y
x
and
y
isTRUE(x)
Test if
x
is
TRUE