Contents
 
Introduction
To R

Subscripts

Subscripts are how R extracts parts of vectors. We use square brackets, and the subscripts start at 1.
> x <- 10:1
> y <- x[2]
> y
[1] 9
Here y gets the value of the second element of x.

Slicing more...

You can extract parts of a vector by subscripting with another vector.
> y <- x[c(1,3,5)]
> y
[1] 10  8  6
> x[4:7]
[1] 7 6 5 4
Here the returned value is a vector.

Don't bite off more than you can chew...

If you try and subscript a vector with a number out of range...
> x[12]
[1] NA
you get NA. This is the symbol R uses for missing data, or other numeric nonsense.

Logical Subscripts

You can use a vector of logical true/false values as a subscript. Example:
> x <- c(6,5,6,4,4,3,4,2,3,4)
> y <- c(5,3,4,2,6,5,4,5,4,3)  couple of random vectors
> xeq4 <- x == 4               which of x equals 4
> xeq4                         
 [1] FALSE FALSE FALSE  TRUE  TRUE FALSE  TRUE FALSE FALSE  TRUE
                              
> y[xeq4]                     which of y correspond to
[1] 2 6 4 3                   x==4?
> y[x == 4]    
[1] 2 6 4 3                   or simply...

Negative Subscripts

Negative subscripts? Whats the -Nth element of a vector? R defines this as being all the vector except the Nth element. This gives us an easy way of removing some elements from a vector.
> x <- 1:10
> x[-3]
[1]  1  2  4  5  6  7  8  9 10   missing 3
> x[c(3,4,7)]
[1] 3 4 7
> x[-c(3,4,7)]                   a vector of negatives
[1]  1  2  5  6  8  9 10
You can't mix positive and negative subscripts. Why would you want to?

Some more examples

> x <- 1:10
> x[-length(x)]                   all but the last
[1] 1 2 3 4 5 6 7 8 9
> x[length(x):1]                  reverse x
[1] 10  9  8  7  6  5  4  3  2  1
There is a function to do this last one: rev(x) - most of the simple things you may want to do tend to have their own functions!

Later you will learn to use the help system to find them.

Complex Number Subscripts

> x <- 1:4
> y <- 8:11
> z2 <- complex(r=x,i=y)
> z2
[1] 1+ 8i 2+ 9i 3+10i 4+11i
> z2[1]+z2[2]
[1] 3+17i

Contents