> x <- c(x[1:3],20,x[4:6]) # insert 20
>x
[1] 12 5 13 20 16 8 20
> x <- x[-2:-4] # delete elements 2 through 4
>x
[1] 12 16 8 20
In the first case,xis originally of length 5, which we extend to 6 via con-
catenation and then reassignment. We didn’t literally change the length of
xbut instead created a new vector fromxand then assignedxto that new
vector.
NOTE Reassignment occurs even when you don’t see it, as you’ll see in Chapter 14.
For instance, even the innocuous-looking assignmentx[2] <- 12is actually a
reassignment.
Analogous operations can be used to change the size of a matrix. For
instance, therbind()(row bind) andcbind()(column bind) functions let you
add rows or columns to a matrix.
> one
[1]1111
>z
[,1] [,2] [,3]
[1,] 1 1 1
[2,] 2 1 0
[3,] 3 0 1
[4,] 4 0 0
> cbind(one,z)
[1,] 1111
[2,] 1210
[3,] 1301
[4,] 1400
Here,cbind()creates a new matrix by combining a column of 1s with the
columns ofz. We choose to get a quick printout, but we could have assigned
the result toz(or another variable), as follows:
z <- cbind(one,z)
Note, too, that we could have relied on recycling:
> cbind(1,z)
[,1] [,2] [,3] [,4]
[1,]1111
[2,]1210
[3,]1301
[4,]1400
74 Chapter 3