Our functionnewbookvec()(line 7) does the construction for this class. In
it, you can see the structure of the class: An object will consist of the vector
itself,vec(line 9), and a vector of write counts,wrts(line 10).
By the way, note in line 11 that the functionclass()itself is a replace-
ment function!
The functions[.bookvec()and[<-.bookvec()are fairly straightforward.
Just remember to return the entire object in the latter.
7.11 Tools for Composing Function Code..........................................
If you are writing a short function that’s needed only temporarily, a quick-
and-dirty way to do this is to write it on the spot, right there in your inter-
active terminal session. Here’s an example:
> g <- function(x) {
+ return(x+1)
+}
This approach obviously is infeasible for longer, more complex func-
tions. Now, let’s look at some better ways to compose R code.
7.11.1 Text Editors and Integrated Development Environments.............
You can use a text editor such as Vim, Emacs, or even Notepad, or an editor
within an integrated development environment (IDE) to write your code in
a file and then read it into R from the file. To do the latter, you can use R’s
source()function.
For instance, suppose we have functionsf()andg()in a filexyz.R.InR,
we give this command:
> source("xyz.R")
This readsf()andg()into R as if we had typed them using the quick-and-
dirty way shown at the beginning of this section.
If you don’t have much code, you can cut and paste from your editor
window to your R window.
Some general-purpose editors have special plug-ins available for R, such
as ESS for Emacs and Vim-R for Vim. There are also IDEs for R, such as the
commercial one by Revolution Analytics, and open source products such as
StatET, JGR, Rcmdr, and RStudio.
7.11.2 The edit() Function..............................................
A nice implication of the fact that functions are objects is that you can edit
functions from within R’s interactive mode. Most R programmers do their
code editing with a text editor in a separate window, but for a small, quick
change, theedit()function can be handy.
186 Chapter 7