Revision 2 as of 2011-09-28 05:33:33

Clear message

Intro to R

R is a language and an environment, that is good for analyzing data and creating rich graphics. To get started make sure you have R installed on your computer. The latest version of R is available at the Comprehensive R Archive Network.

When you start R, an interpreter window is launched. You can type commands into it, or cut and paste them from a document.

Use R as a Calculator

The easiest way to get started is to simply use R as a calculator. Type some numerical expressions into R and see what happens (or cut and paste the code below). The lines that start with "#" are comments do not get evaluated.

# how many seconds in a day?
24*60*60

# what is 2 to the power of 16?
2^16

# what's the square root of pi?
sqrt(22/7)

# generate a series of numbers using the colon character
1:5

# what's the average value of the series of numbers above?
mean(1:5)

The basic elements of R are variables and functions. Look, you've already used two functions! (bonus points: type the word pi on the command line, and you'll see that it's a predefined variable).

Variables

Variables are used to store data so we can operate on it. R has four basic kinds of variables: vector, matrix, dataframe, list. The way we assign data to a variable is to use an assignment operator "<-". An equals sign also works (=, common in other languages), but the convention in R is to use the little arrow.

Let's start with a vector. It can hold one or more values.

# create x and assign it the value of 2
x <- 2

# make other variables
y <- 3.14

# you can name variables using letters, words, periods, underscores
temperature <- 37

temperature2 <- 98.6

# but the name cannot start with a number
2temperature <- 98.6

# we can assign character strings too, but they have to be enclosed in quotes
genotype <- ″wt″