Next: Functions
Up: Introduction to S
Previous: Arithmetic and Logical Operators
Often it will be useful or necessary to work with a subset of a
dataset. There are several ways to do this in S.
- Explicit subscripting, using
a vector of positive integers. For example x[1] will extract the
first element of x. x[1:5] refers to the first five values of x.
x[c(1,3,5)] selects x[1], x[3], and x[5].
- A logical expression of the same length as x.
The elements of x for which the
logical expression is true will be extracted.
For example, x[x>0] selects the
elements of x that are greater than zero. If y is the same length as
x, y[x
>
0] selects the cases from y corresponding to the positive
values of x.
- A vector of negative integers. Subscripting by a negative integer
tells S to omit the cases corresponding to the negative subscripts.
For example, x[-1] selects all but the first
element of x. x[c(-1,-5,-7)]
refers to all but the first, fifth, and seventh elements
of x.
Examples:
> x
[1] 1 2 3 4 5
> x > 3
[1] F F F T T
> x[x>3]
[1] 4 5
> y<-x*x
> y
[1] 1 4 9 16 25
> y[x>3]
[1] 16 25
> y[2]
[1] 4
> y[-2]
[1] 1 9 16 25
Next: Functions
Up: Introduction to S
Previous: Arithmetic and Logical Operators
Albyn Jones
Tue Jun 25 11:03:47 PDT 1996