R tutorial

From "A B C"
Revision as of 02:30, 21 August 2012 by Boris (talk | contribs) (→‎Scripts)
Jump to navigation Jump to search

R tutorial


This page is a placeholder, or under current development; it is here principally to establish the logical framework of the site. The material on this page is correct, but incomplete.


This is a tutorial introduction to R for users with no previous background in the platform or the language.



 

The environment

In this section we discuss how to download and install the software, how to configure an R session and what work with the R environment includes.

Installation

  1. Navigate to http://probability.ca/cran/ [1] and follow the link to your computer's operating system.
  2. Download a precompiled binary (or "build") of the R "framework" to your computer and follow the instructions for installing it. You don't need tools, or GUI versions for now, but do make sure that the program is the correct one for your version of your operating system.
  3. Launch R.

The program should open a window–the "R console"–and greet you with its input prompt, awaiting your input:

>


The sample code on this page sometimes copies input/output from the console, and sometimes shows the actual commands only. The > character at the beginning of the line is always just R's input prompt; It is shown here only to illustrate the interactive use of the program and you do not need to type it. If a line starts with [1] or similar, this is R's output on the console. A #-character this marks the following text as a comment which is not executed by R. In principle, commands can be copied by you and pasted into the console, or into a script - obviously, you don't need to copy the comments. In addition, I use syntax highlighting on R-script, to color language keywords, numbers, strings, etc. different from other text. This improves readability but keep in mind that the colours you see on your computer will be different. One more thing about the console: use your keyboard's up-arrow keys to retrieve previous commands, then enter the line with left-arrow to edit it; hit enter to execute the modified line.

User interface

R comes with a GUI[2] to lay out common tasks. For example, there are a number of menu items, many of which are similar to other programs you will have worked with ("File", "Edit", "Format", "Window", "Help" ...). All of these tasks can also be accessed through the command line. In general, GUIs are useful when you are not sure what you want to do or how to go about it; the command line is much more powerful when you have more experience and know your way around in principle. R gives you both options.

In addition to the Console, there are a number of other windows that you can open (or that open automatically). They all can be brought to the foreground with the Windows menu and include help, plotting, package browser and other windows.

Let's begin with a glossary of some terms that R uses and how they relate to your work:

Help
Help is available for all commands and for the R command line syntax. As well, help is available to find the names of commands when you are not sure of them.


("help" is a function, arguments to a function are passed in parentheses "()")

> help(rnorm)
>


(shorthand for the same thing)

> ?rnorm
>


(what was the name of that again ... ?)

> ?binom     
No documentation for 'binom' in specified packages and libraries:
you could try '??binom'
> ??binom
>


(found "Binomial" in the list of keywords)

> ?Binomial
>


That's all fine, but you wil soon notice that R's help documentation is not all that helpful for the newcomers (who need the most help). If you look at the bottom of the help function, you will usually find examples of command usage; these often make matters more clear than the terse and principled help-text above. Or you can just Google for what interests you and this is often the quickest way to find working example code. Also, as a result of Google search it may turn out for example that something can't be done (easily)–and you won't find things that can't be done at all in the help system. You may want to include "r language" in your search terms, although Google is usually pretty good at figuring out what kind of "r" you are looking for, if your query includes a few terms vaguely related to statistics.

There is also an active R-help mailing list which you can post to–or at least search the archives: your question probably has been asked and answered before.


Working directory

To locate a file in a computer, one has to specify the filename and the directory in which the file is stored; this is sometimes called the path of the file. The "working directory" for R is either the direcory i which the R-program has been installed, or some other directory, as initialized by a startup script. You can execute the command getwd() to list what the "Working Directory" is currently set to:


> getwd()
[1] "/Users/steipe/R"


It is convenient to put all your R-input and output files into a project specific directory and then define this to be the "Working Directory". Use the setwd() command for this. setwd() requires a parameter in its parentheses: a string with the directory path. Strings in R are delimited with " or ' characters. If the directory does not exist, an Error will be reported. Make sure you have created the directory. On Mac and Unix systems, the usual shorthand notation for relative paths can be used: ~ for the home directory, . for the current directory, .. for the parent of the current directory.


My home directory...

> setwd("~") 
> getwd()
[1] "/Users/steipe"

Relative path: home directory, up one level, then down into chen's home directory)

> setwd("~/../chen")  
> getwd()
[1] "/Users/chen"

Absolute path: specify the entire string)

> setwd("/Users/steipe/abc/R_samples")  
> getwd()
[1] "Users/steipe/abc/R_samples"

Task:

  1. Create a directory for your sample files and use setwd("your-directory-name") to set the working directory.
  2. Confirm that this has worked by typing getwd().

The Working Directory functions can also be accessed thorugh the Menu, under Misc.


Workspace

During an R session, you might define a large number of variables, datastructures, load packages and scripts etc. All of this information is stored in the so-called "Workspace". When you quit R you have the option to save the Workspace; it will then be reloaded in your next session.


List the current workspace contents: initially it is empty. (R reports an object of type "character" with a length of 0.)

> ls() 
character(0)
>

Initialize three variables (multiple commands on one line can be separated with a semicolon";")

> a <- 1; b <-2; eps <- 0.0001
> ls() 
[1] "a"   "b"   "eps"
>

Remove one item. (Note: the parameter is not the string "a", but the variable name a.)

> rm(a) 
> ls()
[1] "b"   "eps"
>

We can use the output of ls() as input to rm() to remove everything and clear the Workspace. (cf. ?rm for details)

rm(list= ls()) 
> ls() 
character(0)
>


 

Packages

R has many powerful functions built in, but one of it's greatest features is that it is easily extensible. Extensions have been written by legions of scientists for many years, most commonly in the R programming language itself, and made available through CRAN–The Comprehensive R Archive Network. A package is a collection of code, documentation and sample data files. To use packages, you need to install them (once), and add them to your current session (for every new session). You can get an overview of installed and loaded packages by opening the Package Manager window from the Packages & Data Menu item. It gives a list of available packages you currently have installed, and identifies those that have been loaded at startup, or interactively.

Task:

library() opens a window of installed packages in the library; search() shows which one are currently loaded.

> library()
> search()
 [1] ".GlobalEnv"        "tools:RGUI"        "package:stats"     "package:graphics" 
 [5] "package:grDevices" "package:utils"     "package:datasets"  "package:methods"  
 [9] "Autoloads"         "package:base"


  • In the R packages available window, confirm that seqinr is not yet installed.
  • Follow the link to seqinr to see what standard information is available with a package. Then follow the link to Reference manual to access the documentation pdf. This is also sometimes referred to as a "vignette" and contains usage hints and sample code.

Read the help for vignette. Note that there is a command to extract R sample code from a vignette, to experiment with it.

> ?vignette
>


Install seqinr from the closest CRAN mirror and load it for this session. Explore some functions.

> ??install
> ?install.packages
> install.packages("seqinr")
--- Please select a CRAN mirror for use in this session ---
trying URL 'http://probability.ca/cran/bin/macosx/contrib/2.13/seqinr_3.0-5.tgz'
Content type 'application/x-gzip' length 4528528 bytes (4.3 Mb)
opened URL
==================================================
downloaded 4.3 Mb


The downloaded packages are in
	/var/folders/dq/dqPEEPbF0ApRU/-Tmp-//RtmpBlw/downloaded_packages
> 
> library("seqinr")
> ls("package:seqinr")
  [1] "a"                       "aaa"                     "AAstat"                 
  [4] "acnucclose"              "acnucopen"               "al2bp"                  
     [...]
[205] "where.is.this.acc"       "words"                   "words.pos"              
[208] "write.fasta"             "zscore"                 
> ?a
> a("Tyr")
[1] "Y"
> choosebank()
 [1] "genbank"       "embl"          "emblwgs"       "swissprot"     "ensembl"      
    [...]
 [31] "refseqViruses"
  • The fact that these methods work shows that the library has been downloaded, installed and downloaded and its functions are now available. Just for fun and demonstration, let's use these functions to download a sequence and calculate some statistics (however, not to digress too far, without further explanation at this point). Copy the code below and paste it into the R-console
choosebank("swissprot")
query("seq", "N=MBP1_YEAST")
mbp1 <- getSequence(seq)
closebank()
x <- AAstat(mbp1[[1]])
barplot(sort(x$Compo))


Scripts

My preferred way of running R is not strictly through the console. I open a new file - a script - and enter my R commands into the file. Then I execute the commands directly from the script. I may try things in the console, experiment, change parameters etc. - but ultimately everything I do goes into the file. This has four major advantages:

  • The script is an accurate record of my procedure so I know exactly what I have done;
  • I add numerous comments to record what I was thinking when I developed it;
  • I can immediately reproduce the entire analysis from start and finish, simply by rerunning the script;
  • I can reuse parts easily, thus making new analyses quick to develop.

Task:

  • Use the File menu to open a New Document.
  • Enter the following code (copy from here and paste):
# sample script:
# define a vector
a <- c(1, 1, 2, 3, 5, 8, 13)
# list its contents
a
# calculate the mean of its values
mean(a)
  • save the file (e.g. with the name sample.R).

Placing the cursor in a line and pressing command-return (on the Mac, ctrl-r on Windows) will execute that line and you see the result on the console. You can also select more than one line and execute the selected block with this shortcut. Alternatively, you can run the entire file. In the console type:

source("sample.R")



 

Simple commands

Including functions


 

Scalar datatypes

Definition, change, operations with, functions to work on...

 

Vectors

 

Matrices, tables, frames

Subsetting,mselecting and filtering


 

Data manipulations

Transformation Search


 

Writing functions

 

Installing new functions

 

Numeric output

 

Graphic output

 

Notes

  1. This is the CRAN mirror site at the University of Toronto, any other mirror site will do. You may access a choice of mirror sites from the R-project homepage.
  2. Graphical User Interface


 

Further reading and resources