The Art of R Programming

(WallPaper) #1

6 # construct a new object of class bookvec
7 newbookvec <- function(x) {
8 tmp <- list()
9 tmp$vec <- x # the vector itself
10 tmp$wrts <- rep(0,length(x)) # counts of the writes, one for each element
11 class(tmp) <- "bookvec"
12 return(tmp)
13 }
14
15 # function to read
16 "[.bookvec" <- function(bv,subs) {
17 return(bv$vec[subs])
18 }
19
20 # function to write
21 "[<-.bookvec" <- function(bv,subs,value) {
22 bv$wrts[subs] <- bv$wrts[subs]+1#note the recycling
23 bv$vec[subs] <- value
24 return(bv)
25 }
26 \end{Code}
27
28 Let's test it.
29
30 \begin{Code}
31 > b <- newbookvec(c(3,4,5,5,12,13))
32 >b
33 $vec
34 [1]34551213
35
36 $wrts
37 [1]000000
38
39 attr(,"class")
40 [1] "bookvec"
41 > b[2]
42 [1] 4
43 > b[2] <- 88 # try writing
44 > b[2] # worked?
45 [1] 88
46 > b$wrts # write count incremented?
47 [1]010000


We have named our class"bookvec", because these vectors will do their
own bookkeeping—that is, keep track of write counts. So, the subscripting
functions will be[.bookvec()and[<-.bookvec().

R Programming Structures 185
Free download pdf