The Art of R Programming

(WallPaper) #1
[1] 8 88 5 12 13
> x[3]
[1] 5

> "["(x,3)
[1] 5
> x <- "[<-"(x,2:3,value=99:100)
>x
[1] 8 99 100 12 13

Again, that complicated call in this line:

> x <- "[<-"(x,2:3,value=99:100)

is simply performing what happens behind the scenes when we execute this:

x[2:3] <- 99:100

We can easily verify what’s occurring like so:

> x <- c(8,88,5,12,13)
> x[2:3] <- 99:100
>x
[1] 8 99 100 12 13

7.10.2 Extended Example: A Self-Bookkeeping Vector Class...............


Suppose we have vectors on which we need to keep track of writes. In other
words, when we execute the following:

x[2] <- 8

we would like not only to change the value inx[2]to 8 but also increment
a count of the number of timesx[2]has been written to. We can do this by
writing class-specific versions of the generic replacement functions for vector
subscripting.

NOTE This code uses classes, which we’ll discuss in detail in Chapter 9. For now, all you
need to know is that S3 classes are constructed by creating a list and then anointing it
as a class by calling theclass()function.

1 # class "bookvec" of vectors that count writes of their elements
2
3 # each instance of the class consists of a list whose components are the
4 # vector values and a vector of counts
5

184 Chapter 7

Free download pdf