R Fundamentals II
Reference
Reference for R Fundamentals I
Saving plots
pdfcreates a PDF file (given by argumentfile) ready for receiving graphics.- Arguments
widthandheigthdefine the page size. par(mfrow = c(nr, nc))creates a grid to place multiple graphs on a single page, wherenris the number of rows andncis 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
pngorjpegcan be used instead ofpdffor other file formats.
Writing data
write.tableto write out objects in regular format- Set
quote = FALSEso that text isn’t wrapped in"marks. - Set
row.names = FALSEto not store row names. separgument defines the column separatorwrite.csvhassep = ","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
returnexplictly. - 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
ifcondition to start a conditional statement andelseto 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 && Yis only true if both X and Y areTRUE.X || Yis true if either X or Y, or both, areTRUE.- Zero is considered
FALSE; all other numbers are consideredTRUE. - Use
forif you want to repeat a block of code multiple times with known number of iterations. - Use
whileif you want to repeat a block of code until a condition is met. - Nest loops to operate on multi-dimensional data.
breakbreaks out of a loop.nextmoves to the nex iterations without finishing the current iteration.
Installing and loading packages
install.packagesto install packages from CRANlibraryto load a package into R