R Hackathon 1/Basics

From Phyloinformatics
(Redirected from R Hackathon/Basics)
Jump to: navigation, search

Basics of Using R

Loading packages

Any packages needed for your analysis must be loaded at the beginning of each session in R. To load a package, type at the command prompt:

     library(ape)

Accessing help

You can obtain information about a package (e.g. its authors, a description of what it does, an index of functions) by typing at the command prompt:

     library(help=ape)

You can also get information about specific functions within packages. For example, if you wanted help with the phylogenetically independent constrasts function, pic, you could type:

     ?pic

This command will open a help window with a description of the function and typically an example of how to use it.

To find all documents relating to phylogenetic methods, you could enter:

     help.search("phylogenetic")


Changing working directory

It is useful to keep files associated with analyses in R in a working directory (a folder on your computer). To access this directory, you can use the menu options (File->Change dir.. for Windows and Misc->Change Working Directory on Macs). After changing to your working directory, you can ask R to retrieve input data from this folder (see data input). Also, any items you save will automatically go to this directory.

Saving your work

Analyses in R involve the creation and manipulation of objects (see intro to R), which in the case of comparative analyses might include phylogenetic trees and tip data. You can save the objects created during an R session in several ways. Mac users can select Save Workspace File from the Workspace menu, and PC users can select Save Workspace from the File Menu. Alternately, you can type:

    save.image("mywork.Rdata")

This command will save your work in your current directory. When you re-open R, you can load these object by typing:

    load("mywork.Rdata")

Similarly, you can save the command input during the session as .Rhistory files. This history can be used as a script for repeating or modifying previous analyses (see below).

Scripting

Many users will find it helpful to write a script containing their commands, so that the commands can be copied and pasted into the prompt instead of being typed in each time. R has a built-in editor that makes it easy to create and use scripts. For PC users, select New Script under the File menu. Commands typed into the scripts can be run by highlighting the commands in the script editor and using the CTRL+R or the Run Line or Selection button. Mac users can create scripts by opening a new document and can run commands by highlighting the commands and typing Apple+Return.