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 interactive terminal session. Here’s an example:

> g <- function(x) {
+    return(x+1)
+ }

This approach obviously is infeasible for longer, more complex functions. Now, let’s look at some better ways to compose R code.

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 functions f() and g() in a file xyz.R. In R, we give this command:

> source("xyz.R")

This reads f() and g() 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.

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, the edit() function can be handy.

For instance, we could edit the function f1() by typing this:

> f1 <- edit(f1)

This opens the default editor on the code for f1, which we could then edit and assign back to f1.

Or, we might be interested in having a function f2() very similar to f1() and thus could execute the following:

> f2 <- edit(f1)

This gives us a copy of f1() to start from. We would do a little editing and then save to f2(), as seen in the preceding command.

The editor involved will depend on R’s internal options variable editor. In UNIX-class systems, R will set this from your shell’s EDITOR or VISUAL environment 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 typing the following:

> ?options

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