The Art of R Programming

(WallPaper) #1

[1] "a" "b" "ab"



x
abab
124



Consider one line in particular:


names(x) <- c("a","b","ab")



Looks totally innocuous, eh? Well, no. In fact, it’s outrageous! How on
Earth can we possibly assign a value to the result of a function call? The reso-
lution to this odd state of affairs lies in the R notion ofreplacement functions.
The preceding line of R code actually is the result of executing the
following:


x <- "names<-"(x,value=c("a","b","ab"))


No, this isn’t a typo. The call here is indeed to a function named
names<-(). (We need to insert the quotation marks due to the special char-
acters involved.)


7.10.1 What’s Considered a Replacement Function?......................


Any assignment statement in which the left side is not just an identifier
(meaning a variable name) is considered a replacement function. When
encountering this:


g(u) <- v


R will try to execute this:


u <- "g<-"(u,value=v)


Note the “try” in the preceding sentence. The statement will fail if you
have not previously definedg<-(). Note that the replacement function has
one more argument than the original functiong(), a named argumentvalue,
for reasons explained in this section.
In earlier chapters, you’ve seen this innocent-looking statement:


x[3] <- 8


The left side is not a variable name, so it must be a replacement func-
tion, and indeed it is, as follows.
Subscripting operations are functions. The function"["()is for reading
vector elements, and"[<-"()is used to write. Here’s an example:



x <- c(8,88,5,12,13)
x



R Programming Structures 183
Free download pdf