Intro to R

On this page, only one command is different between R and Splus.

Vector commands

x <- scan("my.dat")
x <- c(4,7,2,9)
length(x)
sum(x)
x + 1
log(x)
x * y
median(x)
mad(x)
x[order(x)]

Factor commands

A factor is a vector of categorical values, usually to label elements of another vector. Right now the only purpose is plotting. Levels are sorted by default.

y <- c("b","b","a","a","a","c")
f <- factor(y)
levels(f)
f <- factor(y,levels=c("b","a","c"))
tapply(x,f,median)
boxplot(x ~ f)            (in R)
boxplot(split(x,f))       (in Splus)

Tables

The variable InsectSprays is a table. A table is a collection of named vectors and factors. For example, InsectSprays has a vector named "count" and a factor named "spray". They are the same length. You can access the columns via $, for example InsectSprays$spray. I suggest copying the columns into shorter names, such as
x <- InsectSprays$count 
f <- InsectSprays$sprays
Now you can use all of the usual vector commands on x and factor commands on f.


Tom Minka
Last modified: Mon Dec 17 14:17:52 EST 2001