The Art of R Programming

(WallPaper) #1
For instance, we could edit the functionf1()by typing this:

> f1 <- edit(f1)

This opens the default editor on the code forf1, which we could then
edit and assign back tof1.
Or, we might be interested in having a functionf2()very similar tof1()
and thus could execute the following:

> f2 <- edit(f1)

This gives us a copy off1()to start from. We would do a little editing and
then save tof2(), as seen in the preceding command.
The editor involved will depend on R’s internal options variableeditor.
In UNIX-class systems, R will set this from your shell’sEDITORorVISUALenvi-
ronment variable, or you can set it yourself, as follows:

> options(editor="/usr/bin/vim")

For more details on using options, see the online documentation by typ-
ing the following:

> ?options

You can useedit()to edit data structures, too.

7.12 Writing Your Own Binary Operations........................................


You can invent your own operations! Just write a function whose name be-
gins and ends with %, with two arguments of a certain type, and a return
value of that type.
For example, here’s a binary operation that adds double the second
operand to the first:

> "%a2b%" <- function(a,b) return(a+2*b)
> 3 %a2b% 5
[1] 13

A less trivial example is given in the section about set operations in Sec-
tion 8.5.

7.13 Anonymous Functions.......................................................


As remarked at several points in this book, the purpose of the R function
function()is to create functions. For instance, consider this code:

inc <- function(x) return(x+1)

R Programming Structures 187
Free download pdf