Note that duplicates are allowed.> x <- c(4,2,17,5)
> y <- x[c(1,1,3)]
>y
[1] 4 4 17Negative subscripts mean that we want to exclude the given elements in
our output.> z <- c(5,12,13)
> z[-1] # exclude element 1
[1] 12 13
> z[-1:-2] # exclude elements 1 through 2
[1] 13In such contexts, it is often useful to use thelength()function. For
instance, suppose we wish to pick up all elements of a vectorzexcept for
the last. The following code will do just that:> z <- c(5,12,13)
> z[1:(length(z)-1)]
[1] 5 12Or more simply:> z[-length(z)]
[1] 5 12This is more general than usingz[1:2]. Our program may need to work
for more than just vectors of length 2, and the second approach would give
us that generality.2.4.3 Generating Useful Vectors with the : Operator.....................
There are a few R operators that are especially useful for creating vectors.
Let’s start with the colon operator:, which was introduced in Chapter 1. It
produces a vector consisting of a range of numbers.> 5:8
[1]5678
> 5:1
[1]5432132 Chapter 2