R Fundamentals II
Reference
Reference for R Fundamentals I
Saving plots
pdf
creates a PDF file (given by argumentfile
) ready for receiving graphics.- Arguments
width
andheigth
define the page size. par(mfrow = c(nr, nc))
creates a grid to place multiple graphs on a single page, wherenr
is the number of rows andnc
is the number of columns of that grid.- Use graphics functions (e.g.
plot
,hist
,boxplot
,abline
,text
, etc.) to send plots into the file. - Close the opened file by
dev.off()
. - Functions
png
orjpeg
can be used instead ofpdf
for other file formats.
Writing data
write.table
to write out objects in regular format- Set
quote = FALSE
so that text isn’t wrapped in"
marks. - Set
row.names = FALSE
to not store row names. sep
argument defines the column separatorwrite.csv
hassep = ","
as default
Functions
- Put code whose parameters change frequently in a function, then call it with different parameter values to customize its behavior.
- Define a function by assigning
function(...)
to a name, where...
stands for one or more arguments. - Enclose the body of a function into
{}
. - The last line of a function is returned, or you can use
return
explictly. - Any code written in the body of the function is isolated to the function when it is called.
- Functions can be nested, i.e. they can call other functions.
- In a function call, when assigning values to function arguments, you must use
=
(and not<-
).
Control flow
- Use
if
condition to start a conditional statement andelse
to provide a default. - Enclose the bodies of the branches of conditional statements into
{ }
, unless the body contains only one line. - Use
==
to test for equality. X && Y
is only true if both X and Y areTRUE
.X || Y
is true if either X or Y, or both, areTRUE
.- Zero is considered
FALSE
; all other numbers are consideredTRUE
. - Use
for
if you want to repeat a block of code multiple times with known number of iterations. - Use
while
if you want to repeat a block of code until a condition is met. - Nest loops to operate on multi-dimensional data.
break
breaks out of a loop.next
moves to the nex iterations without finishing the current iteration.
Installing and loading packages
install.packages
to install packages from CRANlibrary
to load a package into R