#LyX 2.3 created this file. For more info see http://www.lyx.org/
\lyxformat 544
\begin_document
\begin_header
\save_transient_properties true
\origin unavailable
\textclass scrartcl
\begin_preamble
%\VignetteIndexEntry{Rchaeology}

\usepackage{Sweavel}
\usepackage{graphicx}
\usepackage{color}

\usepackage{babel}
\usepackage[samesize]{cancel}



\usepackage{ifthen}

\makeatletter

\renewenvironment{figure}[1][]{%

 \ifthenelse{\equal{#1}{}}{%

   \@float{figure}

 }{%

   \@float{figure}[#1]%

 }%

 \centering

}{%

 \end@float

}

\renewenvironment{table}[1][]{%

 \ifthenelse{\equal{#1}{}}{%

   \@float{table}

 }{%

   \@float{table}[#1]%

 }%

 \centering

%  \setlength{\@tempdima}{\abovecaptionskip}%

%  \setlength{\abovecaptionskip}{\belowcaptionskip}%

% \setlength{\belowcaptionskip}{\@tempdima}%

}{%

 \end@float

}


%\usepackage{listings}
% Make ordinary listings look as if they come from Sweave
\lstset{tabsize=2, breaklines=true,style=Rstyle}

% In document Latex options:
\fvset{listparameters={\setlength{\topsep}{0em}}}
\def\Sweavesize{\scriptsize} 
\def\Rcolor{\color{black}} 
\def\Rbackground{\color[gray]{0.90}}



\usepackage{babel}

\usepackage[samesize]{cancel}



\usepackage{ifthen}



\usepackage{listings}% Make ordinary listings look as if they come from Sweave
\lstset{tabsize=2, breaklines=true, style=Rstyle}
\end_preamble
\options noae
\use_default_options false
\begin_modules
sweave
enumitem
logicalmkup
\end_modules
\maintain_unincluded_children false
\language american
\language_package default
\inputencoding utf8
\fontencoding T1
\font_roman "lmodern" "default"
\font_sans "lmss" "default"
\font_typewriter "lmtt" "default"
\font_math "auto" "auto"
\font_default_family default
\use_non_tex_fonts false
\font_sc false
\font_osf false
\font_sf_scale 100 100
\font_tt_scale 100 100
\use_microtype false
\use_dash_ligatures true
\graphics default
\default_output_format default
\output_sync 0
\bibtex_command default
\index_command default
\paperfontsize default
\spacing single
\use_hyperref true
\pdf_bookmarks true
\pdf_bookmarksnumbered false
\pdf_bookmarksopen false
\pdf_bookmarksopenlevel 1
\pdf_breaklinks false
\pdf_pdfborder false
\pdf_colorlinks false
\pdf_backref section
\pdf_pdfusetitle true
\papersize default
\use_geometry true
\use_package amsmath 1
\use_package amssymb 1
\use_package cancel 1
\use_package esint 1
\use_package mathdots 0
\use_package mathtools 1
\use_package mhchem 0
\use_package stackrel 1
\use_package stmaryrd 1
\use_package undertilde 1
\cite_engine natbib
\cite_engine_type authoryear
\biblio_style plainnat
\use_bibtopic false
\use_indices false
\paperorientation portrait
\suppress_date false
\justification true
\use_refstyle 0
\use_minted 0
\index Index
\shortcut idx
\color #008000
\end_index
\leftmargin 1in
\topmargin 1in
\rightmargin 1in
\bottommargin 1in
\secnumdepth 3
\tocdepth 3
\paragraph_separation skip
\defskip smallskip
\is_math_indent 0
\math_numbering_side default
\quotes_style english
\dynamic_quotes 0
\papercolumns 1
\papersides 1
\paperpagestyle default
\tracking_changes false
\output_changes false
\html_math_output 0
\html_css_as_file 0
\html_be_strict false
\end_header

\begin_body

\begin_layout Title
Rchaeology: Idioms of R Programming
\end_layout

\begin_layout Author
Paul E.
 Johnson <pauljohn @ ku.edu>
\end_layout

\begin_layout Standard
This document was initiated on May 31, 2012.
 The newest copy will always be available at 
\begin_inset Flex URL
status open

\begin_layout Plain Layout

http://pj.freefaculty.org/R
\end_layout

\end_inset

 and as a vignette in the R package 
\begin_inset Quotes eld
\end_inset

rockchalk
\begin_inset Quotes erd
\end_inset

.
\end_layout

\begin_layout Description
Rchaeology: The study of R programming by investigation of R source code.
 It is the effort to discern the programming strategies, idioms, and style
 of R programmers in order to better communicate with them.
\end_layout

\begin_layout Description
Rchaeologist: One who practices Rchaeology.
\end_layout

\begin_layout Standard
These are Rcheological observations about the style and mannerisms of R
 programmers in their native habitats.
 Almost all of the insights here are gathered from the r-help and r-devel
 emails lists, the stackoverflow website pages for R, and the R source code
 itself.
 These are lessons from the 
\begin_inset Quotes eld
\end_inset

school of hard knocks.
\begin_inset Quotes erd
\end_inset


\end_layout

\begin_layout Standard
How is this different from Rtips(
\begin_inset Flex URL
status open

\begin_layout Plain Layout

http://pj.freefaculty.org/R/Rtips.{pdf,html}
\end_layout

\end_inset

)?
\end_layout

\begin_layout Enumerate
This is oriented toward programming R, rather than using R.
\end_layout

\begin_layout Enumerate
It is more synthetic, aimed more at finding 
\begin_inset Quotes eld
\end_inset

what's right
\begin_inset Quotes erd
\end_inset

 rather than 
\begin_inset Quotes eld
\end_inset

what works.
\begin_inset Quotes erd
\end_inset


\end_layout

\begin_layout Enumerate
It is written with Sweave (using Harrell's Sweavel style) so that code examples
 work.
\end_layout

\begin_layout Standard
Where did the 
\begin_inset Quotes eld
\end_inset

R Style
\begin_inset Quotes erd
\end_inset

 section go? It was removed to a separate vignette, RStyle, in the rockchalk
 package.
\end_layout

\begin_layout Standard
\begin_inset CommandInset toc
LatexCommand tableofcontents

\end_inset


\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<echo=F>>=
\end_layout

\begin_layout Plain Layout

dir.create("plots", showWarnings=F)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

% In document Latex options:
\end_layout

\begin_layout Plain Layout


\backslash
fvset{listparameters={
\backslash
setlength{
\backslash
topsep}{0em}}}
\end_layout

\begin_layout Plain Layout


\backslash
SweaveOpts{prefix.string=plots/plot,ae=F,height=4,width=6}
\end_layout

\end_inset


\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<Roptions, echo=F>>=
\end_layout

\begin_layout Plain Layout

options(width=100, continue="  ")
\end_layout

\begin_layout Plain Layout

options(useFancyQuotes = FALSE) 
\end_layout

\begin_layout Plain Layout

set.seed(12345)
\end_layout

\begin_layout Plain Layout

pdf.options(onefile=F,family="Times",pointsize=12)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Section
Introduction: R Idioms.
\end_layout

\begin_layout Standard
This vignette is about the R idioms I have learned while working on the
 rockchalk package.
 At the current time, I don't understand all of the R idioms that are common
 in the advanced R programmers' conversation, but I am getting some traction.
\end_layout

\begin_layout Standard
There is a language gap between an R user and an R programmer.
 Users write 
\begin_inset Quotes eld
\end_inset

scripts
\begin_inset Quotes erd
\end_inset

 that use functions from R packages.
 Users don't write (many) functions.
 Users don't make packages.
 And many users are happy to keep it that way.
 For users who want to become programmers, there is usually a harsh awakening.
 R for development is a different language.
 Well, that's wrong.
 It is a different dialect.
 
\end_layout

\begin_layout Standard
A transitional R user will have to learn a lot of terminology and undergo
 a change of paradigm.
 There are resources available! Everybody should subscribe to the email
 lists for the R project (
\begin_inset Flex URL
status collapsed

\begin_layout Plain Layout

http://www.r-project.org/mail.html
\end_layout

\end_inset

), especially r-help (for user questions) and r-devel.
 Rchaeologically speaking, that is the native habitat of the R programmers.
 There is also a burgeoning collection of blogs and Web forums, perhaps
 most notably the R section on StackExchange (
\begin_inset Flex URL
status collapsed

\begin_layout Plain Layout

http://stackoverflow.com/questions/tagged/r
\end_layout

\end_inset

).
 Excellent books have been published.
 As an Rcheologist, I am drawn to the books that are written by the R insiders.
 
\emph on
S Programming
\emph default
, by William Venables and Brian Ripley 
\begin_inset CommandInset citation
LatexCommand citeyearpar
key "venables_s_2000"
literal "true"

\end_inset

, is a classic.
 Books by pioneering developers Robert Gentleman, 
\emph on
R Programming for Bioinformatics
\emph default
 (2009), and John Chambers, 
\emph on
Software for Data Analysis
\emph default
 
\begin_inset CommandInset citation
LatexCommand citeyearpar
key "chambers_software_2008"
literal "true"

\end_inset

, are, well, awesome.
 In 2012, I started teaching R programming using Norman Matloff's, 
\emph on
The Art of R Programming
\emph default
 (2012), which I think is great and recommend strongly (even though Professor
 Matloff is not one of the R Core Team members, so far as I know).
 
\end_layout

\begin_layout Standard
There are now three types of object-oriented programming in R (S3, S4, and
 reference classes) and the programmer is apparently free to select among
 them without prejudice.
 The best brief explanation of S3 that I've found is in Friedrich Leisch's
 brief note about R packaging, 
\begin_inset Quotes eld
\end_inset

Creating R Packages: A Tutorial
\begin_inset Quotes erd
\end_inset

 (2009).
 One should be mindful of the fact that R is provided with several manuals,
 one of which is the 
\emph on
R Language Definition
\emph default
.
 I find that one difficult to understand, and I usually can't understand
 it until I search through the R source code and packages for usage examples.
\end_layout

\begin_layout Standard
I usually approach R coding in three phases.
 I write code that 
\begin_inset Quotes eld
\end_inset

works
\begin_inset Quotes erd
\end_inset

, however tedious and slow it might be.
 There will be a lot of 
\begin_inset Quotes eld
\end_inset

copy and paste
\begin_inset Quotes erd
\end_inset

 constructions with tedious, manual editing of commands.
 Then I read through the code and look for repetitious elements, and I re-organi
ze to make functions that abstract that work.
 If there are any stanzas that look mostly the same, except that 
\begin_inset Quotes eld
\end_inset

x1
\begin_inset Quotes erd
\end_inset

 is repalced by 
\begin_inset Quotes eld
\end_inset

x2
\begin_inset Quotes erd
\end_inset

, I know the work is not done.
 Finally, I look through the code to find 
\begin_inset Quotes eld
\end_inset

dumb
\begin_inset Quotes erd
\end_inset

 constructions that can be cleaned up and completed with fewer lines.
 A dumb construction is one that I would be ashamed to show to an expert
 R programmer.
\end_layout

\begin_layout Standard
Beginning R programmers, the ones who have never studied C or Java or Fortran,
 will often become 
\begin_inset Quotes eld
\end_inset

stuck
\begin_inset Quotes erd
\end_inset

 in stage one of that process.
 Experienced programmers with more formal training will usually have the
 
\begin_inset Quotes eld
\end_inset

little voice
\begin_inset Quotes erd
\end_inset

 in the back of their minds saying 
\begin_inset Quotes eld
\end_inset

there's a better way,
\begin_inset Quotes erd
\end_inset

 and, unfortunately, R novices don't hear that voice.
 Lacking some of the discipline imposed by those other languages, the usual
 
\begin_inset Quotes eld
\end_inset

rambling
\begin_inset Quotes erd
\end_inset

 R script will seem 
\begin_inset Quotes eld
\end_inset

good enough.
\begin_inset Quotes erd
\end_inset

 The first step for the transitional R programmer, the one who does not
 want to be a novice any more, is to take a harsh look at the code that
 has already been written.
\end_layout

\begin_layout Standard
The rockchalk package has many functions that receive fitted regression
 models and re-arrange their components for re-fitting or plotting.
 A good deal of the advice I have to offer is about the process of managing
 R formula, but I have also accumulated some lessons in argument handling.
 
\end_layout

\begin_layout Section
do.call(), eval(), substitute(), formula().
\end_layout

\begin_layout Standard
If the transitional programmer understands these four functions, she/he
 will be well on the way to escaping the category of novice R programmer.
 The other benefit is that the code written by the experts, including the
 R source code itself, will become much more understandable.
\end_layout

\begin_layout Subsection
Rewriting Formulas.
 My Introductory Puzzle.
\end_layout

\begin_layout Standard
On May 29, 2012, I was working on a regression problem in the rockchalk
 package.
 I have a number of functions that receive elementary regressions and then
 change them.
 I need to receive a fitted model, extract the formula, change some variables,
 and then revise the formula to match the new variables.
 And then run the model over again.
 
\end_layout

\begin_layout Standard
The functions meanCenter() and residualCenter() receive a fitted regression
 model, transform some variables, and then fit a new regression.
 Suppose a regression has been fitted as 
\begin_inset Quotes eld
\end_inset


\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
y ~ x1*x2
\end_layout

\end_inset


\begin_inset Quotes erd
\end_inset

.
 The R result will estimate a predictive formula such as 
\begin_inset Formula $\hat{y}_{i}=\hat{\beta}_{0}+\hat{\beta}_{1}x1_{i}+\hat{\beta}_{2}x2_{i}++\hat{\beta}_{3}x1_{i}\cdot x2_{i}$
\end_inset

.
 meanCenter() will replace the non-centered variables 
\begin_inset Quotes eld
\end_inset

x1
\begin_inset Quotes erd
\end_inset

 and 
\begin_inset Quotes eld
\end_inset

x2
\begin_inset Quotes erd
\end_inset

 with mean-centered variables 
\begin_inset Quotes eld
\end_inset

x1c
\begin_inset Quotes erd
\end_inset

 and 
\begin_inset Quotes eld
\end_inset

x2c
\begin_inset Quotes erd
\end_inset

.
 The original formula y ~ x1*x2 must be replaced with y ~ x1c*x2c.
 I found this to be a very complicated problem with a very satisfying answer.
 
\end_layout

\begin_layout Standard
My first effort used R's update function.
 That is the most obvious approach.
 I learned very quickly that update() is not sufficient.
 It is fairly easy to replace x1 with x1c in the formula, but not when x1
 is logged or otherwise transformed.
 Here is the runable example code that demonstrates the problem.
 
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<include=T, results=hide>>=
\end_layout

\begin_layout Plain Layout

dat <- data.frame(x1 = rnorm(100, m = 50), x2 = rnorm(100, m = 50),
\end_layout

\begin_layout Plain Layout

  x3 = rnorm(100, m = 50), x4 = rnorm(100, m=50), y = rnorm(100))
\end_layout

\begin_layout Plain Layout

m2 <- lm(y ~ log(x1) + x2*x3, data = dat)
\end_layout

\begin_layout Plain Layout

suffixX <- function(fmla, x, s){
\end_layout

\begin_layout Plain Layout

    upform <- as.formula(paste(".
 ~ .", "-", x, "+", paste(x, s, sep = ""), sep="", collapse=
\begin_inset Quotes erd
\end_inset

 
\begin_inset Quotes eld
\end_inset

))
\end_layout

\begin_layout Plain Layout

    update.formula(fmla, upform)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

newFmla <- formula(m2)
\end_layout

\begin_layout Plain Layout

newFmla
\end_layout

\begin_layout Plain Layout

suffixX(newFmla, "x2", "c")
\end_layout

\begin_layout Plain Layout

suffixX(newFmla, "x1", "c")
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Run that and check the last few lines of the output.
 See how the update misses x1 inside log(x1) or in the interaction?
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

> newFmla <- formula(m2)
\end_layout

\begin_layout Plain Layout

> newFmla
\end_layout

\begin_layout Plain Layout

y ~ log(x1) + x2 * x3
\end_layout

\begin_layout Plain Layout

> suffixX(newFmla, "x2", "c")
\end_layout

\begin_layout Plain Layout

y ~ log(x1) + x3 + x2c + x2:x3
\end_layout

\begin_layout Plain Layout

> suffixX(newFmla, "x1", "c")
\end_layout

\begin_layout Plain Layout

y ~ log(x1) + x2 + x3 + x1c + x2:x3
\end_layout

\end_inset


\end_layout

\begin_layout Standard
I asked the members of r-help for assistance.
 Lately I've had very good luck with r-help.
 Gabor Grothendieck wrote an answer to r-help on May 29, 2012.
 He said simply, 
\begin_inset Quotes eld
\end_inset

Try substitute,
\begin_inset Quotes erd
\end_inset

 with this example.
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

> do.call("substitute", list(newFmla, setNames(list(as.name("x1c")), "x1")))
\end_layout

\begin_layout Plain Layout

y ~ log(x1c) + x2 * x3
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Problem solved, in a single line.
 
\end_layout

\begin_layout Standard
That's very clever, I think.
 It packs together a half-dozen very deep thoughts.
 It has most of the essential secrets of R's guts, laid out in a single
 line.
 It has do.call(), substitute(), it interprets a formula as a list, and it
 shows that every command in R is, when it comes down to brass tacks, a
 list.
 
\end_layout

\begin_layout Standard
I would like to take up these separate pieces in order.
\end_layout

\begin_layout Subsection
A Formula Object is a List.
\end_layout

\begin_layout Standard
While struggling with this, I noticed this really interesting pattern.
 The solution depends on it.
 The object 
\begin_inset Quotes eld
\end_inset

newFmla
\begin_inset Quotes erd
\end_inset

 is not just a text string.
 It prints out as if it were text, but it is actually an R list object.
 Its parts can be probed recursively, to eventually reveal all of the individual
 pieces:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<newFla10>>=
\end_layout

\begin_layout Plain Layout

newFmla
\end_layout

\begin_layout Plain Layout

newFmla[[1]]
\end_layout

\begin_layout Plain Layout

newFmla[[2]]
\end_layout

\begin_layout Plain Layout

newFmla[[3]]
\end_layout

\begin_layout Plain Layout

newFmla[[3]][[2]]
\end_layout

\begin_layout Plain Layout

newFmla[[3]][[2]][[2]]
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
How could I put that information to use? Read on.
\end_layout

\begin_layout Subsection
do.call() and eval()
\end_layout

\begin_layout Standard
In my early work as an Rchaeologist, I had noticed eval() and do.call(),
 but did not understand their significance.
 Coming to grips with these ideas is a critical step in the R programmer's
 growth, because they separate the 
\begin_inset Quotes eld
\end_inset

script writer
\begin_inset Quotes erd
\end_inset

 from the 
\begin_inset Quotes eld
\end_inset

language programmer.
\begin_inset Quotes erd
\end_inset

 Whenever difficult problems arise in r-help, the answer almost invariably
 involves do.call() or eval().
 
\end_layout

\begin_layout Subsubsection
do.call()
\end_layout

\begin_layout Standard
Let's concentrate on do.call first.
 The syntax is like this
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

do.call("someRFunction", aListOfArgumentsToGoInTheParentheses)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
It is as if we were telling R to run this:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

someRFunction(aListOfArgumentsToGoInTheParentheses)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
We use do.call() because it is much more flexible than calling someRFunction()
 directly.
\end_layout

\begin_layout Standard
Let's consider an example that runs a regression the ordinary way, and then
 with do.call.
 In this example, the role of 
\begin_inset Quotes eld
\end_inset

someRFunction
\begin_inset Quotes erd
\end_inset

 will be played by lm() and the list of arguments will be the parameters
 of the regression.
 The regression m1 will be constructed the ordinary way, while m2 is constructed
 with do.call().
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

m1 <- lm(y ~ x1*x2, data = dat)
\end_layout

\begin_layout Plain Layout

coef(m1)
\end_layout

\begin_layout Plain Layout

regargs <- list(formula = y ~ x1*x2, data = quote(dat))
\end_layout

\begin_layout Plain Layout

m2 <- do.call("lm", regargs)
\end_layout

\begin_layout Plain Layout

coef(m2)
\end_layout

\begin_layout Plain Layout

all.equal(m1, m2)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
The object regargs is a list of arguments that R can understand when they
 are supplied to the lm function.
 
\end_layout

\begin_layout Standard
do.call() is a powerful, mysterious symbol.
 It holds flexibility; we can calculate 
\begin_inset Quotes eld
\end_inset

on the language
\begin_inset Quotes erd
\end_inset

 to create commands and then run them.
 I first needed do.call() when we had a simulation project that ran very
 slowly.
 There's a writeup in the working examples distributed with rockchalk called
 stackListItems-01.R.
 I was using rbind() over and over to join the results of simulation runs.
 Basically, the code was like this
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

for (i in 1:10000){
\end_layout

\begin_layout Plain Layout

   dat <- someHugeSimulation(i)
\end_layout

\begin_layout Plain Layout

   result <- rbind(result, dat)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\end_inset


\end_layout

\begin_layout Standard
That will call rbind() 10000 times.
 I had not realized that rbind() is time-consuming.
 It accesses a new chunk of memory each time it is run.
 On the other hand, we could collect those results in a list, then we can
 call rbind() one time to smash together all of the results.
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

for (i in 1:10000){
\end_layout

\begin_layout Plain Layout

   mylist[[i]] <- someHugeSimulation(i)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

result <- do.call("rbind", mylist)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
It is much faster to run rbind() only once.
 It would be OK if we typed it all out like this:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

result <- rbind(mylist[[1]], mylist[[2]], mylist[[3]], ..., mylist[[10000])
\end_layout

\end_inset


\end_layout

\begin_layout Standard
But who wants to do all of that typing? How tiresome! Thanks to Erik Iverson
 in r-help, I understand that
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

result <- do.call("rbind", mylist)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
is doing the EXACT same thing.
 
\begin_inset Quotes eld
\end_inset

mylist
\begin_inset Quotes erd
\end_inset

 is a list of arguments.
 do.call is 
\emph on
constructing
\emph default
 a function call from the list of arguments.
 It is 
\emph on
as if
\emph default
 I had actually typed rbind with 10000 arguments.
\end_layout

\begin_layout Standard
The beauty in this is that we could design a program that can assemble the
 list of arguments, and also choose the function to be run, on the fly.
 We are not required to literally write the function in quotes, as in 
\begin_inset Quotes eld
\end_inset

rbind
\begin_inset Quotes erd
\end_inset

.
 We could instead have a variable that is calculated to select one function
 among many, and then use do.call on that.
 In a very real sense, we could write a program that can write itself as
 it runs.
 
\end_layout

\begin_layout Standard
From all of this (and a peek at ?call), I arrive at an Rchaeological eureka!
 A call object is a quoted command plus a list of arguments for that command.
 
\end_layout

\begin_layout Subsubsection
eval()
\end_layout

\begin_layout Standard
Where does eval() fit into the picture? do.call() manufactures a call and
 executes it immediately.
 It is possible to arrest the process mid stream, to capture the call without
 evaluating it with eval().
 The terminology in the R documentation on this is difficult, mainly because
 there are several different ways to create a piece of not-yet-evaluated
 code.
 By 
\begin_inset Flex Strong
status collapsed

\begin_layout Plain Layout
not-yet-evaluated code
\end_layout

\end_inset

, I mean an 
\begin_inset Quotes eld
\end_inset

unevaluated expression
\begin_inset Quotes erd
\end_inset

 or a 
\begin_inset Quotes eld
\end_inset

call object
\begin_inset Quotes erd
\end_inset

, anything that can be handled by the eval() function.
 A not-yet-evaluated object holds some syntax that can we need later.
 I think of do.call() as a contraction of 
\begin_inset Quotes eld
\end_inset

eval
\begin_inset Quotes erd
\end_inset

 and 
\begin_inset Quotes eld
\end_inset

call
\begin_inset Quotes erd
\end_inset

.
 As far as I can tell, do.call("lm", list(arguments)) is the same as eval(call(
\begin_inset Quotes eld
\end_inset

lm
\begin_inset Quotes erd
\end_inset

, arguments)).
 
\end_layout

\begin_layout Standard
There are many ways to ask R to create the not-yet-evaluated object, that's
 one of the confusing things (in my opinion).
 Most obviously, call() function can be used for that.
 But functions like quote() and expression() can also create not-yet-evaluated
 code.
\end_layout

\begin_layout Standard
Everybody has experienced an error like this:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

> x1 + x2
\end_layout

\begin_layout Plain Layout

Error: object 'x1' not found
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Whenever we use a variable, the R interpreter expects to find it.
 We know those variables are in the data frame dat, but the interpreter
 does not know that's what we mean.
 But we can ask R to trust us with the quote() function, which, basically,
 means 
\begin_inset Quotes eld
\end_inset

here's some code we will evaluate later
\begin_inset Quotes erd
\end_inset

:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

> mycall <- quote(x1 + x2)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
The object 
\begin_inset Quotes eld
\end_inset

mycall
\begin_inset Quotes erd
\end_inset

 is an R call object, something that might be evaluated in the future.
 
\end_layout

\begin_layout Standard
When we want to evaluate 
\begin_inset Quotes eld
\end_inset

x1 + x2
\begin_inset Quotes erd
\end_inset

, we ask R do to so:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

eval(mycall, dat)
\end_layout

\end_inset

The second argument supplies the place where x1 and x2 are to be found.
 R users may never have noticed the eval() function, but most will have
 used the with() function, which is simply a clever re-phrasing of the eval
 function's interface.
 It does the same thing:
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

with(dat, x1 + x2)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
and so does 
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

with(dat, eval(mycall)).
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Now, back to the regression example we were working on before.
 We can create the call object using the call() function, which requires
 the name of a function and a comma-separated list of quoted arguments.
 I quote each of the bits of syntax in the arguments because I don't want
 R to replace 
\begin_inset Quotes eld
\end_inset

dat
\begin_inset Quotes erd
\end_inset

 with the actual data frame, I only want it to remember the name.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

m3 <- lm(y ~ x1*x2, data = dat)
\end_layout

\begin_layout Plain Layout

coef(m3)
\end_layout

\begin_layout Plain Layout

mycall <- call("lm", quote(y ~ x1*x2), data = quote(dat))
\end_layout

\begin_layout Plain Layout

m4 <- eval(mycall)
\end_layout

\begin_layout Plain Layout

coef(m4)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
The main reason for using eval is that we can 
\begin_inset Quotes eld
\end_inset

piece together
\begin_inset Quotes erd
\end_inset

 commands and then run them after we have assembled all the pieces.
 The nickname for this seems to be 
\begin_inset Quotes eld
\end_inset

computing on the language.
\begin_inset Quotes erd
\end_inset

 There is a discussion of it in the R Language Definition.
 It is also surveyed in Hadley Wickham's new book, 
\emph on
Advanced R
\emph default
 
\begin_inset CommandInset citation
LatexCommand citeyearpar
key "Wickham2015"
literal "true"

\end_inset

.
\end_layout

\begin_layout Standard
Did you ever notice that you get an error if you run 
\begin_inset Quotes eld
\end_inset

x1 + x2
\begin_inset Quotes erd
\end_inset

, but if you run 
\begin_inset Quotes eld
\end_inset

y 
\begin_inset Formula $\sim$
\end_inset

 x1 + x2
\begin_inset Quotes erd
\end_inset

, then there is no error? It is as if R is wrapping your code in protective
 tissue, something like quote().
 However, the protective wrapper in this case is actually the function called
 formula().
 The R interpreter notices the symbol 
\begin_inset Formula $\sim$
\end_inset

 in the syntax, and so it assumes you meant to run
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

formula(y ~ x1 + x2)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
A formula is another kind of not-yet-evaluated thing.
 It is something that we can fiddle with before evaluating.
 
\end_layout

\begin_layout Standard
Create a complicated formula.
 Note that the lm function receives that formula object without trouble.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

f1 <- y ~ x1 + x2 + x3 + log(x4)
\end_layout

\begin_layout Plain Layout

class(f1)
\end_layout

\begin_layout Plain Layout

m5 <- lm(f1, data = dat)
\end_layout

\begin_layout Plain Layout

coef(m5)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
The object f1 is a formula object.
 Its not just a text string.
 Observe it has separate pieces, just like newFmla in the example problem
 that started this section.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

f1[[1]]
\end_layout

\begin_layout Plain Layout

f1[[2]]
\end_layout

\begin_layout Plain Layout

f1[[3]]
\end_layout

\begin_layout Plain Layout

f1[[3]][[1]]
\end_layout

\begin_layout Plain Layout

f1[[3]][[2]]
\end_layout

\begin_layout Plain Layout

f1[[3]][[3]]
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\begin_inset Newline newline
\end_inset

Note that f1 created in this way must be a syntactically valid R formula;
 it cannot include any other regression options.
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

> f1 <- y ~ x1 + x2 + x3 + log(x4), data=dat 
\end_layout

\begin_layout Plain Layout

Error: unexpected ',' in "f1 <- y ~ x1 + x2 + x3 + log(x4),"
\end_layout

\end_inset


\end_layout

\begin_layout Standard
If I declare f1exp as an expression, then R does not re-interpret it as
 a formula (f1exp is an unevaluated expression, the R parser has not translated
 it yet).
 To use that as a formula in the regression, we have to evaluate it.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

f1exp <- expression(y ~ x1 + x2 + x3 + log(x4))
\end_layout

\begin_layout Plain Layout

class(f1exp)
\end_layout

\begin_layout Plain Layout

m6 <- lm(eval(f1exp), data = dat)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
When f1exp is evaluated, what do we have? Here's the answer.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

f1expeval <- eval(f1exp)
\end_layout

\begin_layout Plain Layout

class(f1expeval)
\end_layout

\begin_layout Plain Layout

all.equal(f1expeval, f1)
\end_layout

\begin_layout Plain Layout

m7 <- lm(f1expeval, data=dat)
\end_layout

\begin_layout Plain Layout

all.equal(coef(m6), coef(m7))	
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
The point here is that the pieces of an ordinary use command can be separated
 and put back together again before the work of doing calculations begins.
 We can edit the formula.
 Suppose we replace a part:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

f1[[3]][[2]] <- quote(x1 + log(x2))
\end_layout

\begin_layout Plain Layout

m8 <- lm(f1, data = dat)
\end_layout

\begin_layout Plain Layout

coef(m8)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Now we turn back to the main theme.
 How is eval() used in functions? Some functions take a lot of arguments.
 We may want to do a lot of fine tuning on the arguments, before they are
 assembled and evaluated.
 Hence, it is very important that we can keep some bits of R that are symbolic,
 rather than calculated, until we need them.
 
\end_layout

\begin_layout Standard
If you are looking for examples of eval() in the R source code, there is
 a nice one in the beginning of the lm() function.
 Suppose a user submits a command like 
\begin_inset Quotes eld
\end_inset

lm(y ~ x, data = dat, x = TRUE, y = TRUE).
\begin_inset Quotes erd
\end_inset

 Inside lm(), the import is re-organized.
 Here are the first lines of the lm() function
\end_layout

\begin_layout Standard
\begin_inset listings
lstparams "breaklines=true,numbers=left,numberstyle={\footnotesize},tabsize=4"
inline false
status open

\begin_layout Plain Layout

lm <- function (formula, data, subset, weights, na.action, method = "qr",
\end_layout

\begin_layout Plain Layout

    model = TRUE, x = FALSE, y = FALSE, qr = TRUE, singular.ok = TRUE,
\end_layout

\begin_layout Plain Layout

    contrasts = NULL, offset, ...)
\end_layout

\begin_layout Plain Layout

{
\end_layout

\begin_layout Plain Layout

    ret.x <- x
\end_layout

\begin_layout Plain Layout

    ret.y <- y
\end_layout

\begin_layout Plain Layout

    cl <- match.call()
\end_layout

\begin_layout Plain Layout

    mf <- match.call(expand.dots = FALSE)
\end_layout

\begin_layout Plain Layout

    m <- match(c("formula", "data", "subset", "weights", "na.action",
\end_layout

\begin_layout Plain Layout

        "offset"), names(mf), 0L)
\end_layout

\begin_layout Plain Layout

    mf <- mf[c(1L, m)]
\end_layout

\begin_layout Plain Layout

    mf$drop.unused.levels <- TRUE
\end_layout

\begin_layout Plain Layout

    mf[[1L]] <- as.name("model.frame")
\end_layout

\begin_layout Plain Layout

    mf <- eval(mf, parent.frame())
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Now suppose we turn on the debugger and run a regression in R with a command
 like this.
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

debug(lm)
\end_layout

\begin_layout Plain Layout

m1 <- lm(y ~ x1 * x2, data = dat, x = TRUE, y = TRUE)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
After that, we are 
\begin_inset Quotes eld
\end_inset

in
\begin_inset Quotes erd
\end_inset

 the function, stepping through line-by-line.
 In line 8, the match.call() function is used to grab a copy of the command
 that I typed.
 We can see that mf is exactly the same as my command, except R has named
 the arguments:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

> mf
\end_layout

\begin_layout Plain Layout

lm(formula = y ~ x1 * x2, data = dat, x = TRUE, y = TRUE)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
That's not just a string of letters, however.
 It is a call object, a list with individual pieces that can be revised.
 Recall that the first element in a call object is the name of a function,
 and the following elements are the arguments.
 Lines 10 and 11 check the names of mf for the presence of certain arguments,
 and throw away the rest.
 It only wants the arguments we would be needed to run the function model.frame.
 Line 12 adds an argument to the list, drop.unused.levels.
 Up to that point, then, we can look at the individual pieces of mf:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

> names(mf) 
\end_layout

\begin_layout Plain Layout

[1] ""      "formula"       "data" [4] "drop.unused.levels"
\end_layout

\begin_layout Plain Layout

> mf[[1]]
\end_layout

\begin_layout Plain Layout

lm
\end_layout

\begin_layout Plain Layout

> mf[[2]]
\end_layout

\begin_layout Plain Layout

y ~ x1 * x2
\end_layout

\begin_layout Plain Layout

> mf[[3]]
\end_layout

\begin_layout Plain Layout

dat
\end_layout

\begin_layout Plain Layout

> mf[[4]] 
\end_layout

\begin_layout Plain Layout

[1] TRUE
\end_layout

\end_inset


\end_layout

\begin_layout Standard
The object mf has separate pieces that can be revised and then evaluated.
 Line 13 replaces the element 1 in mf with the symbol 
\begin_inset Quotes eld
\end_inset

model.frame
\begin_inset Quotes erd
\end_inset

.
 That's the function that will be called.
 Line 14 is the coup de grâce, when the revised call 
\begin_inset Quotes eld
\end_inset

mf
\begin_inset Quotes erd
\end_inset

 is sent to eval.
 In the end, it is 
\emph on
as if
\emph default
 lm had directly submitted the command
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

mf <- model.frame(y ~ x1 * x2, data = dat, drop.unused.levels = TRUE)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
It would not do to simply write that into the lm function, however, because
 some people use variables that have names different from y, x1, and x2,
 and their data objects may not be called dat.
 lm allows users to input whatever they want for a formula and data, and
 then lm takes what it needs to build a model frame.
\end_layout

\begin_layout Subsection
substitute()
\end_layout

\begin_layout Standard
Most R users I know have not used substitute, except possibly if they try
 to use plotmath.
 In the context of plotmath, the problem is as follows.
 Plotmath causes the R plot functions to convert expressions into mathematical
 symbols in a way that is reminiscent of \SpecialChar LaTeX
.
 For example, a command like this:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

text(4, 4, expression(gamma))
\end_layout

\end_inset

will draw the gamma symbol at the position (4,4).
 We can use paste to combine symbolic commands and text like so:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

text(4, 4, expression(paste(gamma, " = 7")))
\end_layout

\end_inset

The number 7 is a nice number, but what if we want to calculate something
 and insert it into the expression? Your first guess might be to insert
 a function that makes a calculation, such as the mean, but this fails:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

text(4, 4, expression(paste(gamma, mean(x))))
\end_layout

\end_inset

In order to smuggle the result of a calculation into an expression, some
 fancy footwork is required.
 In the help page for plotmath, examples using the functions bquote and
 substitute are offered.
 I have found this to be quite frustrating and difficult to do, and if one
 examines my collection of examples on 
\begin_inset Flex URL
status open

\begin_layout Plain Layout

http://pj.freefaculty.org/R/WorkingExamples
\end_layout

\end_inset

, one will find quite a few plotmath exercises.
\end_layout

\begin_layout Standard
For the particular purpose of blending expressions with calculation results,
 I find the bquote function to be more easily understandable.
 However, when going beyond plotmath, I expect most R programmers will need
 to use substitute() instead, so I will discuss that in this section.
 The plotmath help page points to syntax like this:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<fig=T, height=3, width=4>>=
\end_layout

\begin_layout Plain Layout

plot(1:10, seq(1,5, length.out=10), type = "n", main="Illustrating Substitute
 with plotmath", xlab="x", ylab="y")
\end_layout

\begin_layout Plain Layout

text(5, 4, substitute(gamma + x1mean, list(x1mean = mean(dat$x1))))
\end_layout

\begin_layout Plain Layout

text(5, 2, expression(paste(gamma, " plus the mean of x1")))
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Run ?substitute and one is brought to a famous piece of Rchaeological pottery:
 
\end_layout

\begin_layout Quote
‘substitute’ returns the parse tree for the (unevaluated) expression ‘expr’,
 substituting any variables bound in ‘env’.
 
\end_layout

\begin_layout Standard
Pardon me.
 parse tree? We've seen expressions already, that part is not so off putting.
 But 
\begin_inset Quotes eld
\end_inset

parse tree
\begin_inset Quotes erd
\end_inset

? Really?
\end_layout

\begin_layout Standard
This is one of those points at which being an Rchaeologist has real benefits.
 We have to dig deeper, to try to understand not only what the R programmer
 says, but what she is actually trying to do.
 The manual page gives us some insights into the R programmer, and it is
 his or her view of his or her own actions, but it doesn't necessarily speak
 to how we should understand substitute().
 
\end_layout

\begin_layout Standard
For me, the only workable approach is to build up a sequence of increasingly
 complicated examples.
 I start by creating the list of replacements.
 This replacement list can have a format like this: 
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

sublist <- list(x1 = "alphabet", x2 = "zoology")
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Suppose I have some other object in which x1 and x2 need to be replaced.
 Specifically, when an expression has 
\begin_inset Quotes eld
\end_inset

x1
\begin_inset Quotes erd
\end_inset

, I want 
\begin_inset Quotes eld
\end_inset

alphabet
\begin_inset Quotes erd
\end_inset

, and 
\begin_inset Quotes eld
\end_inset

x2
\begin_inset Quotes erd
\end_inset

 should become 
\begin_inset Quotes eld
\end_inset

zoology.
\begin_inset Quotes erd
\end_inset

 The quotes in the R code indicate that alphabet and zoology are character
 strings, not other objects that already exist.
 Consider replacing x1 and x2 in x1 + x2 + log(x1) + x3:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

substitute(expression(x1 + x2 + log(x1) + x3), sublist)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Note that the substitution 1) leaves other variables alone (since they are
 not named in sublist) and 2) it finds all valid uses of the symbols x1
 and x2 and replaces them.
\end_layout

\begin_layout Standard
This isn't quite what I wanted, however, because the strings have been inserted
 into the middle of my expression.
 I don't want text.
 I just want symbols.
 I've seen the conversion from character to symbol done with as.symbol()
 and with as.name(), recently I realized that they are synonymous.
 I usually use as.symbol() because that name has more intuition for me, but
 in Gabor's answer to my question, as.name() is used.
 Using as.name(), my example would become:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

sublist <- list(x1 = as.name("alphabet"), x2 = as.name("zoology"))
\end_layout

\begin_layout Plain Layout

substitute(expression(x1 + x2 + log(x1) + x3), sublist)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Subsection
setNames and names
\end_layout

\begin_layout Standard
Almost every R user has noticed that the elements of R lists can have names.
 In a data frame, the names of the list elements are thought of as variable
 names, or column names.
 If dat is a data frame, the names and colnames functions return the same
 thing, but that's not true for other types of objects.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

dat <- data.frame(x1=1:10, x2=10:1, x3=rep(1:5,2), x4=gl(2,5))
\end_layout

\begin_layout Plain Layout

colnames(dat)
\end_layout

\begin_layout Plain Layout

names(dat)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
After dat is created, we can change the names inside it with a very similar
 approach:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

newnames <- c("whatever","sounds","good","tome")
\end_layout

\begin_layout Plain Layout

colnames(dat) <- newnames
\end_layout

\begin_layout Plain Layout

colnames(dat)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
While used interactively, this is convenient, but it is a bit tedious because
 we have to create dat first, and then set the names.
 The setNames() function allows us to do this in one shot.
 I'll paste the data frame creating commands and the name vector in for
 a first try:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

dat2 <- setNames(data.frame(x1 = rnorm(10), x2 = rnorm(10),
\end_layout

\begin_layout Plain Layout

    x3 = rnorm(10), x4 = gl(2,5)), c("good", "names", "tough", "find"))
\end_layout

\begin_layout Plain Layout

head(dat2, 2)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
In order to make this more generally useful, the first step is to take the
 data-frame-creating code and set it into an expression that is not immediately
 evaluated (that's datcommand in what follows).
 When I want the data frame to be created, I use eval(), and then the newnames
 vector is put to use.
 
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

newnames <- c("iVar", "uVar", "heVar", "sheVar")
\end_layout

\begin_layout Plain Layout

datcommand <- expression(data.frame(x1=1:10, x2=10:1, x3=rep(1:5,2), x4=gl(2,5)))
\end_layout

\begin_layout Plain Layout

eval(datcommand)
\end_layout

\begin_layout Plain Layout

dat3 <- setNames(eval(datcommand), newnames)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
The whole point of this exercise is that we can write code that creates
 the names, and creates the data frame, and then they all come together.
\end_layout

\begin_layout Standard
What if we have just one element in a list? In Gabor's answer to my question,
 there is this idiom
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

setNames(list(as.name("x1c")), "x1")))
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Consider this from the inside out.
 
\end_layout

\begin_layout Enumerate
as.name(
\begin_inset Quotes eld
\end_inset

x1c
\begin_inset Quotes erd
\end_inset

) is an R symbol object,
\end_layout

\begin_layout Enumerate
list(as.name(
\begin_inset Quotes eld
\end_inset

x1c
\begin_inset Quotes erd
\end_inset

)) is a list with just one object, which is that symbol object.
 
\end_layout

\begin_layout Enumerate
Use setNames().
 The object has no name! We would like to name it 
\begin_inset Quotes eld
\end_inset

x1
\begin_inset Quotes erd
\end_inset

.
 
\end_layout

\begin_layout Standard
It is as if we had run the command list(x1 = x1c).
 The big difference, of course, is that this way is much more flexible because
 we can calculate replacements.
 
\end_layout

\begin_layout Subsection
The Big Finish
\end_layout

\begin_layout Standard
In the meanCenter() function in rockchalk, some predictors are mean-centered
 and their names are revised.
 A variable named 
\begin_inset Quotes eld
\end_inset

age
\begin_inset Quotes erd
\end_inset

 becomes 
\begin_inset Quotes eld
\end_inset

agec
\begin_inset Quotes erd
\end_inset

 or 
\begin_inset Quotes eld
\end_inset

x1
\begin_inset Quotes erd
\end_inset

 becomes 
\begin_inset Quotes eld
\end_inset

x1c
\begin_inset Quotes erd
\end_inset

.
 So the user's regression formula that uses variables age or x1 must be
 revised.
 This is a function that takes a formula 
\begin_inset Quotes eld
\end_inset

fmla
\begin_inset Quotes erd
\end_inset

 and replaces a symbol xname with newname.
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

formulaReplace <- function(fmla, xname, newname){ 
\end_layout

\begin_layout Plain Layout

    do.call("substitute", list(fmla, setNames(list(as.name(newname)), xname)))
 
\end_layout

\begin_layout Plain Layout

}
\end_layout

\end_inset


\end_layout

\begin_layout Standard
This is put to use in meanCenter().
 Suppose a vector of variable names called nc (stands for 
\begin_inset Quotes eld
\end_inset

needs centering
\begin_inset Quotes erd
\end_inset

) has already been calculated.
 The function std() creates a centered variable.
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

newFmla <- mc$formula
\end_layout

\begin_layout Plain Layout

for (i in seq_along(nc)){
\end_layout

\begin_layout Plain Layout

    icenter <- std(stddat[, nc[i]])
\end_layout

\begin_layout Plain Layout

    newname <- paste(as.character(nc[i]), "c", sep = "")
\end_layout

\begin_layout Plain Layout

    newFmla <- formulaReplace(newFmla,  as.character(nc[i]), newname)
\end_layout

\begin_layout Plain Layout

    nc[i] <- newname
\end_layout

\begin_layout Plain Layout

}
\end_layout

\end_inset


\end_layout

\begin_layout Standard
If one has a copy of rockchalk 1.6 or newer, the evidence of the success
 of this approach should be evident in the output of the command example(meanCen
ter).
 
\end_layout

\begin_layout Section
Make Re-Usable Tools (Rather than Cutting and Pasting)
\end_layout

\begin_layout Standard
We seek concise solutions that are generalizable.
 It is almost never right to cut and paste and then make minor edits in
 each copy to achieve particular purposes.
 This advice goes against the grain of the graduate students that I work
 with.
 They will almost always use cut and paste solutions.
 
\end_layout

\begin_layout Standard
Here is an example of the problem.
 A person needed 
\begin_inset Quotes eld
\end_inset

dummy variables
\begin_inset Quotes erd
\end_inset

.
 The code had several pages like this:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

  if(setcorr == 1){
\end_layout

\begin_layout Plain Layout

        corr.10 <-1
\end_layout

\begin_layout Plain Layout

        corr.20 <-0
\end_layout

\begin_layout Plain Layout

        corr.30 <-0
\end_layout

\begin_layout Plain Layout

        corr.40 <-0
\end_layout

\begin_layout Plain Layout

        corr.50 <-0
\end_layout

\begin_layout Plain Layout

        corr.60 <-0
\end_layout

\begin_layout Plain Layout

        corr.70 <-0
\end_layout

\begin_layout Plain Layout

        corr.80 <-0
\end_layout

\begin_layout Plain Layout

    }
\end_layout

\begin_layout Plain Layout

    if(setcorr == 2){
\end_layout

\begin_layout Plain Layout

        corr.10 <-1
\end_layout

\begin_layout Plain Layout

        corr.20 <-1
\end_layout

\begin_layout Plain Layout

        corr.30 <-0
\end_layout

\begin_layout Plain Layout

        corr.40 <-0
\end_layout

\begin_layout Plain Layout

        corr.50 <-0
\end_layout

\begin_layout Plain Layout

        corr.60 <-0
\end_layout

\begin_layout Plain Layout

        corr.70 <-0
\end_layout

\begin_layout Plain Layout

        corr.80 <-0
\end_layout

\begin_layout Plain Layout

    }
\end_layout

\begin_layout Plain Layout

    if(setcorr == 3){
\end_layout

\begin_layout Plain Layout

        corr.10 <-1
\end_layout

\begin_layout Plain Layout

        corr.20 <-1
\end_layout

\begin_layout Plain Layout

        corr.30 <-1
\end_layout

\begin_layout Plain Layout

        corr.40 <-0
\end_layout

\begin_layout Plain Layout

        corr.50 <-0
\end_layout

\begin_layout Plain Layout

        corr.60 <-0
\end_layout

\begin_layout Plain Layout

        corr.70 <-0
\end_layout

\begin_layout Plain Layout

        corr.80 <-0
\end_layout

\begin_layout Plain Layout

    }
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Well, that's understandable, but a little bit embarrassing.
 I asked 
\begin_inset Quotes eld
\end_inset

why do you declare these separate variables, why not make a vector?
\begin_inset Quotes erd
\end_inset

 and 
\begin_inset Quotes eld
\end_inset

can't you see a more succinct way to declare those things?
\begin_inset Quotes erd
\end_inset

 The answer is 
\begin_inset Quotes eld
\end_inset

we do it that way in SAS
\begin_inset Quotes erd
\end_inset

 or 
\begin_inset Quotes eld
\end_inset

this runs
\begin_inset Quotes erd
\end_inset

.
 One might suspect that the author was eager to say, 
\begin_inset Quotes eld
\end_inset

my project is based on 10,000 lines of R code
\begin_inset Quotes erd
\end_inset

 in order to impress a lay audience.
\end_layout

\begin_layout Standard
If the mission is to create a vector with a certain number of 1's at the
 beginning, surely either of these functions would be better:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

biVec1 <- function(n = 3, n1s = 1) {
\end_layout

\begin_layout Plain Layout

    c(rep(1, n1s), rep(0, n - n1s))
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

\end_layout

\begin_layout Plain Layout

biVec2 <- function(n = 3, n1s = 1){
\end_layout

\begin_layout Plain Layout

    x <- numeric(length = n)
\end_layout

\begin_layout Plain Layout

    x[1:n1s] <- 1
\end_layout

\begin_layout Plain Layout

    x
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

\end_layout

\begin_layout Plain Layout

(corr <- biVec1(n = 8, n1s = 3))
\end_layout

\begin_layout Plain Layout

(corr <- biVec2(n = 8, n1s = 3))
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
The cut and paste way is not wrong, exactly.
 Its tedious.
 
\end_layout

\begin_layout Standard
I think any reasonable user should want a vector, rather than the separate
 variables.
 But suppose the user is determined, and really wants the individual variables
 named corr.10, corr.20, and so forth.
 We can re-design this so that those variables will be sitting out in the
 workspace after the function is run.
 Read help(
\begin_inset Quotes eld
\end_inset

assign
\begin_inset Quotes erd
\end_inset

) and try
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

biVec3 <- function(n = 3, n1s = 1) {
\end_layout

\begin_layout Plain Layout

    X <- c(rep(1, n1s), rep(0, n - n1s))
\end_layout

\begin_layout Plain Layout

    xnam <- paste("corr.", 1:8, "0", sep = "")
\end_layout

\begin_layout Plain Layout

    for(i in 1:n) assign(xnam[i], X[i], envir = .GlobalEnv) 
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

ls()
\end_layout

\begin_layout Plain Layout

biVec3(n = 8, n1s = 3)
\end_layout

\begin_layout Plain Layout

ls()
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
I don't think most people will actually want that kind of result, but if
 they do, there is a way to get it.
\end_layout

\begin_layout Standard
If we want to turn biVec1() or biVec2() into general purpose functions,
 we need to start thinking about the problem of unexpected user input.
 Notice what happens if we ask for more 1's than the result vector is supposed
 to contain:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

> biVec1(n = 3, n1s = 7)
\end_layout

\begin_layout Plain Layout

Error in rep(0, n - n1s) (from #2) : invalid 'times' argument
\end_layout

\begin_layout Plain Layout

> biVec2(n = 3, n1s = 7)
\end_layout

\begin_layout Plain Layout

[1] 1 1 1 1 1 1 1
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Perhaps I prefer biVec1() because it throws an error when there is unreasonable
 input, while biVec2() returns a longer vector than expected with no error.
 
\end_layout

\begin_layout Standard
If the user mistakenly enters non-integers, neither function generates an
 error, and they give us unexpected output.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

biVec1(3.3, 1.8)
\end_layout

\begin_layout Plain Layout

biVec2(3.3, 1.8)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
To my surprise, it is not an easy thing to ask a number if it is a whole
 number (see help(
\begin_inset Quotes eld
\end_inset

is.integer
\begin_inset Quotes erd
\end_inset

)).
 For that, we introduce a new function, is.wholenumber(), and put it to use
 in our new and improved function
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

is.wholenumber <- function(x, tol = .Machine$double.eps^0.5){
\end_layout

\begin_layout Plain Layout

 abs(x - round(x)) < tol
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

\end_layout

\begin_layout Plain Layout

biVec1 <- function(n = 3, n1s = 1) {
\end_layout

\begin_layout Plain Layout

    if(!(is.wholenumber(n) & is.wholenumber(n1s)))
\end_layout

\begin_layout Plain Layout

        stop("Both n and n1s must be whole numbers (integers)")
\end_layout

\begin_layout Plain Layout

    if(n1s > n)
\end_layout

\begin_layout Plain Layout

        stop("n must be greater than or equal to n1s")
\end_layout

\begin_layout Plain Layout

    c(rep(1, n1s), rep(0, n - n1s))
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
In all of the test cases I've tried, that works, although the real numbers
 7.0 and 4.0 are able to masquerade as integers.
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

> biVec1(3, 7)
\end_layout

\begin_layout Plain Layout

Error in biVec1(3, 7) (from #4) : n must be greater than or equal to n1s
\end_layout

\begin_layout Plain Layout

> biVec1(7, 3)
\end_layout

\begin_layout Plain Layout

[1] 1 1 1 0 0 0 0
\end_layout

\begin_layout Plain Layout

> biVec1(3.3, 4.4)
\end_layout

\begin_layout Plain Layout

Error in biVec1(3.3, 4.4) (from #2) : 
\end_layout

\begin_layout Plain Layout

  Both n and n1s must be whole numbers (integers)
\end_layout

\begin_layout Plain Layout

> biVec1(7.0, 4.0)
\end_layout

\begin_layout Plain Layout

[1] 1 1 1 1 0 0 0
\end_layout

\begin_layout Plain Layout

> biVec1(7.0, 4.0)
\end_layout

\begin_layout Plain Layout

[1] 1 1 1 1 0 0 0
\end_layout

\end_inset


\end_layout

\begin_layout Section
Function Arguments.
\end_layout

\begin_layout Standard
While developing functions for the rockchalk package, one of the most important
 learning experiences I've had is in argument management.
 
\end_layout

\begin_layout Standard
One of the reasons that it is difficult to design functions is that there
 is no 
\begin_inset Quotes eld
\end_inset

mandatory manual
\begin_inset Quotes erd
\end_inset

 on this.
 The R framework allows programmer creativity, which is a good thing.
 But it is also a bad thing, since every programmer has his/her own opinion
 about what ought to be done.
 To state the obvious, argument names should be clear, unambiguous, convenient,
 short, and minimally necessary.
 
\end_layout

\begin_layout Standard
Beyond that, what can we say? I urge new R programmers to study the R source
 code.
 This is part of the Rchaeological method.
 Study the most frequently used functions in the R distribution.
 I've learned the most from the way arguments are handled in the functions
 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
hist
\end_layout

\end_inset

(), 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
lm()
\end_layout

\end_inset

, 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
plot()
\end_layout

\end_inset

 and 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
termplot()
\end_layout

\end_inset

.
 These functions have had the most eyes on them and, therefore, they are
 most likely to use the best approach.
 I wrote several functions that eventually went into rockchalk before I
 realized that important fact and I regret it (on a weekly basis).
\end_layout

\begin_layout Standard
In this section, I offer this advice.
\end_layout

\begin_layout Enumerate
Protect your function's calculations from the user's workspace.
\end_layout

\begin_layout Enumerate
Check argument values.
\end_layout

\begin_layout Enumerate
Design the function so that it runs with a minimum number of arguments.
\end_layout

\begin_layout Subsection
A few tidits about arguments
\end_layout

\begin_layout Standard
R includes several functions that are very helpful in dealing with arguments.
\end_layout

\begin_layout Description
missing() Inside a function, such as 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
plotme()
\end_layout

\end_inset

 we often need to check if the user supplied a value for an argument, such
 as 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
col
\end_layout

\end_inset

.
 If the user did not supply a value, we might construct one from the other
 input
\begin_inset Separator latexpar
\end_inset


\end_layout

\begin_deeper
\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

if (missing(col)) col <- someTediousCalculation(y, z)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
This is usually good enough, but there is danger that the user might have
 called the function like so:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

plotme(x, y, z, col = NULL)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
This outsmarts missing(col), which will return FALSE.
 If our goal is to make sure col is something, some non-NULL thing, a more
 careful argument check would be
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

if (missing(col) | is.null(col)) col <- someTediousCalculation(y, z)
\end_layout

\end_inset


\end_layout

\end_deeper
\begin_layout Description
stop() Halts a function and returns a message to the user.
 Usage example 
\begin_inset Separator latexpar
\end_inset


\end_layout

\begin_deeper
\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

if (isTRUE(x)) stop(paste("I'm sorry, you failed to supply the right information.
")))
\end_layout

\end_inset


\end_layout

\end_deeper
\begin_layout Description
stopifnot() It is so frequent to run 
\begin_inset Quotes eld
\end_inset


\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
if(isTRUE(x)) stop()
\end_layout

\end_inset


\begin_inset Quotes erd
\end_inset

 that they created a wrapper, 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
stopifnot(x)
\end_layout

\end_inset

.
\end_layout

\begin_layout Description
warning() If you don't want the function to fail, but you need to warn the
 user about a condition that seems dubious, run
\begin_inset Separator latexpar
\end_inset


\end_layout

\begin_deeper
\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

if (isTRUE(x)) warning(paste("Are you sure the value of x ought to be",
 x, "?"))
\end_layout

\end_inset


\end_layout

\end_deeper
\begin_layout Description
deparse(substitute()) Inside a function, it is often important to find out
 the symbolic value of the argument that the user supplied to the function.
 I don't mean the 
\emph on
value
\emph default
, but rather the symbolic name.
 To see what I mean, run this
\begin_inset Separator latexpar
\end_inset


\end_layout

\begin_deeper
\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<eval=F>>=
\end_layout

\begin_layout Plain Layout

dat <- data.frame(myx = c(1, 2, 3), myy = c(10, 5, 1))
\end_layout

\begin_layout Plain Layout

debug(plot.default)
\end_layout

\begin_layout Plain Layout

plot(dat$myx, dat$myy)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
After you hit enter, the R debugger/browser will come open and the prompt
 will allow you to inspect the situation.
 First, type 
\begin_inset Quotes eld
\end_inset

n
\begin_inset Quotes erd
\end_inset

 and hit return.
 That takes the first step into the calculations.
 After that, run 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
match.call()
\end_layout

\end_inset

.
 The function is somewhat 
\begin_inset Quotes eld
\end_inset

self aware
\begin_inset Quotes erd
\end_inset

.
 It knows how it was called.
 You should see this
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

Browse[2]> n 
\end_layout

\begin_layout Plain Layout

debug: localAxiis <- function(..., col, bg, pch, cex, lty, lwd) Axis(...)
\end_layout

\begin_layout Plain Layout

Browse[2]> match.call()
\end_layout

\begin_layout Plain Layout

plot.default(x = dat$myx, y = dat$myy)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
You asked for 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
plot()
\end_layout

\end_inset

, R sends the work to 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
plot.default()
\end_layout

\end_inset

.
 All is well.
\end_layout

\begin_layout Standard
Still inside the debugger now, type 
\begin_inset Quotes eld
\end_inset

x
\begin_inset Quotes erd
\end_inset

 and then 
\begin_inset Quotes eld
\end_inset

myx
\begin_inset Quotes erd
\end_inset

:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

Browse[2]> x
\end_layout

\begin_layout Plain Layout

[1] 1 2 3
\end_layout

\begin_layout Plain Layout

Browse[2]> myx
\end_layout

\begin_layout Plain Layout

Error: object 'myx' not found
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Inside the function, the vector value that we passed in, which was referred
 to as dat$myx, is now called x.
 The thing x is a data holder, it is used in the following calculations.
 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
x
\end_layout

\end_inset

 does not remember that its passed-in value was named 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
dat$myx
\end_layout

\end_inset

 in a previous life.
 It is as if 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
x
\end_layout

\end_inset

 is the new identity of the same old data vector.
 However, we can ask 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
x
\end_layout

\end_inset

 
\begin_inset Quotes eld
\end_inset

what name were you known by in your previous life?
\begin_inset Quotes erd
\end_inset

 with this interesting idiom.
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

Browse[2]> deparse(substitute(x))
\end_layout

\begin_layout Plain Layout

[1] "dat$myx"
\end_layout

\end_inset


\end_layout

\begin_layout Standard
The substitute() function, as we have already seen, is a way to replace
 a letter x with a value from somewhere.
 Maybe it would be more obvious to run this in 2 steps.
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

Browse[2]> xsubs <- substitute(x)
\end_layout

\begin_layout Plain Layout

Browse[2]> xsubs
\end_layout

\begin_layout Plain Layout

dat$myx
\end_layout

\begin_layout Plain Layout

Browse[2]> deparse(xsubs)
\end_layout

\begin_layout Plain Layout

[1] "dat$myx"
\end_layout

\end_inset


\end_layout

\begin_layout Standard
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
substitute()
\end_layout

\end_inset

 grabs the object name from whence 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
x
\end_layout

\end_inset

 was calculated.
 We need to convert that back to a character string so that we can know
 the symbolic name of the thing that eventually became 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
x
\end_layout

\end_inset

.
 This is at the outer boundary of my R comprehension, so I better stop here.
\end_layout

\begin_layout Standard
Incidentally, you can go exploring in the debugger.
 Run some standards like 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
ls()
\end_layout

\end_inset

 to see what's available.
 If you keep hitting return, the function will run line by line.
 If you get tired of hitting return, type 
\begin_inset Quotes eld
\end_inset

c
\begin_inset Quotes erd
\end_inset

 and the function will run to its conclusion.
 To let R know that you don't want to debug that function any more, run:
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

> undebug(plot.default)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
If you don't do that, then the function browser will pop open every time
 you try to run plot.
\end_layout

\end_deeper
\begin_layout Description
list(...) The three periods, 
\begin_inset Quotes eld
\end_inset

...
\begin_inset Quotes erd
\end_inset

, are a valid word.
 (A period is a valid character).
 R scans user syntax for function arguments and it uses whatever it can
 understand (formal named arguments, positional matching), and then the
 other arguments are thrown into a thing called 
\begin_inset Quotes eld
\end_inset

...
\begin_inset Quotes erd
\end_inset

.
\begin_inset Separator latexpar
\end_inset


\end_layout

\begin_deeper
\begin_layout Standard
In a simple case, we could just pass those additional arguments to another
 function, as in
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

plotme <- function(x, y, ...){
\end_layout

\begin_layout Plain Layout

    plot(x, y, ...)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Often, it is not sufficient to simply pass on the 
\begin_inset Quotes eld
\end_inset

...
\begin_inset Quotes erd
\end_inset

 variables, and we instead need to scan them and sort them for various purposes.
 Inside the function, we access those variables by turning them into a list:
 
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout


\backslash
begin{Sinput}
\end_layout

\begin_layout Plain Layout

dots <- list(...)
\end_layout

\begin_layout Plain Layout


\backslash
end{Sinput}
\end_layout

\end_inset


\end_layout

\begin_layout Standard
We can still pass on the dots to other functions, but the usual problem
 is that some of the arguments in dots may be intended for several different
 functions.
 Suppose we are writing a plotter for categorical variables.
 We might need to receive some arguments, then run 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
table()
\end_layout

\end_inset

, then run 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
layout()
\end_layout

\end_inset

, then run 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
mosaicplot()
\end_layout

\end_inset

.
 The user may have put in arguments intended for those separate functions.
 There's a chance of an error, or at least a warning, if irrelevant arguments
 are passed to those arguments.
 
\end_layout

\begin_layout Standard
The rockchalk functions 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
plotSlopes()
\end_layout

\end_inset

 has examples that do this work.
 They separate the dot arguments that are needed for the 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
predict()
\end_layout

\end_inset

 function and the 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
plot()
\end_layout

\end_inset

 function.
 Because I was learning about arguments when I wrote those functions, I
 did not take the cleanest or most direct route to do this, but they do
 stand as working examples that users can review.
\end_layout

\begin_layout Standard
A function may set a number of defaults that we want to use when the users
 do not supply a lot of details.
 In a case like that, it is useful to remember a very handy function in
 R called 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
modifyList()
\end_layout

\end_inset

.
 The basic idea is that we can build a list of default arguments for a function,
 and then we can scan the 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
dots
\end_layout

\end_inset

 list and it will replace the defaults in the first with changes in the
 second.
 There's an example in rockchalk's 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
pctable()
\end_layout

\end_inset

 function.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout


\backslash
begin{Sinput}
\end_layout

\begin_layout Plain Layout

dots <- list(...)
\end_layout

\begin_layout Plain Layout

dotnames <- names(dots)
\end_layout

\begin_layout Plain Layout

tableargs <- list(rv, cv, dnn = c(rvlab, cvlab))
\end_layout

\begin_layout Plain Layout

newargs <- modifyList(tableargs, dots, keep.null = TRUE)
\end_layout

\begin_layout Plain Layout

t1 <- do.call("table", newargs)
\end_layout

\begin_layout Plain Layout


\backslash
end{Sinput}
\end_layout

\end_inset

The dots list, by definition, is named arguments, and it is often handy
 to have a copy of their names for checking whether an argument is included
 in the list.
 In the plotSlopes() function, here's what I ended up with:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout


\backslash
begin{Sinput}
\end_layout

\begin_layout Plain Layout

validForPredict <- c("se.fit", "dispersion", "terms", "na.action",
\end_layout

\begin_layout Plain Layout

                     "level", "pred.var", "weights")
\end_layout

\begin_layout Plain Layout

dotsForPredict <- dotnames[dotnames %in% validForPredict]
\end_layout

\begin_layout Plain Layout

if (length(dotsForPredict) > 0) {
\end_layout

\begin_layout Plain Layout

    parms <- modifyList(parms, dotargs[dotsForPredict])
\end_layout

\begin_layout Plain Layout

    dotargs[[dotsForPredict]] <- NULL
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

np <- do.call("predictCI", parms)
\end_layout

\begin_layout Plain Layout


\backslash
end{Sinput}
\end_layout

\end_inset

This scans dotnames for elements in the list of arguments that are valid
 for the predict method, and after they are put onto the parms list, then
 those arguments are set to NULL in the dotargs collection.
 Looking at that now, I see it would have been more clear to use 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
setdiff()
\end_layout

\end_inset

 on dotargs to clean that up.
\end_layout

\begin_layout Standard
The central challenge in that work is to find out the names of the arguments
 that are intended for one function, then remove them from 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
dots
\end_layout

\end_inset

 so that they are not passed to a subsequent function that needs them.
 How can one know what arguments are needed? This requires some experience,
 but the first step is to read the interface documentation of the function
 being considered.
 A shortcut is to run the function 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
formals()
\end_layout

\end_inset

, which prints out the names of the function being considered.
 This can sometimes be deceptive for implementations of generic methods.
 Observe that the return from the generic is not so informative as the return
 from the method:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

formals(plot)
\end_layout

\begin_layout Plain Layout

formals(plot.default)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
If a method is not exported, if it does not show as 
\begin_inset Quotes eld
\end_inset

visible
\begin_inset Quotes erd
\end_inset

 in the output from 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
methods(plot)
\end_layout

\end_inset

, then a little more fancy footwork is required to see all of the legal
 arguments.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

formals(graphics:::plot.histogram)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\end_deeper
\begin_layout Subsection
Protect your function's calculations from the user's workspace.
\end_layout

\begin_layout Standard
In the early days of using R, around 2000, it was possible for a user to
 obliterate base functions.
 I recall working on a model about Democratic and Republican voters.
 I created a variable named 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
rep
\end_layout

\end_inset

 and, after that, the 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
lm()
\end_layout

\end_inset

 and 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
plot()
\end_layout

\end_inset

 functions would not work.
 I wrote to r-help about this and learned that my 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
rep
\end_layout

\end_inset

 had obliterated the built-in function 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
rep()
\end_layout

\end_inset

, which is vital in many calculations.
 Shortly after that, R was improved to protect functions from obliteration
 in that way.
 Today I tried to cause mischief by re-defining rep in a number of ways
 and it appears to me the problem is completely solved.
\end_layout

\begin_layout Standard
There has also been a problem that users sometime use the variable names
 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
T
\end_layout

\end_inset

 and 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
F
\end_layout

\end_inset

.
 Recall that R allows 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
T
\end_layout

\end_inset

 as an abbreviation for 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
TRUE
\end_layout

\end_inset

 and 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
F
\end_layout

\end_inset

 for 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
FALSE
\end_layout

\end_inset

.
 R will allow the user to re-define T and F in ways that will break calculations.
 However, R will not allow the user to re-define TRUE or FALSE.
 Observe
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

> TRUE <- 2342 
\end_layout

\begin_layout Plain Layout

Error in TRUE <- 2342 : invalid (do_set) left-hand side to assignment
\end_layout

\begin_layout Plain Layout

> FALSE <- function(x,y){x + y}
\end_layout

\begin_layout Plain Layout

Error in FALSE <- function(x, y) { :
\end_layout

\begin_layout Plain Layout

  invalid (do_set) left-hand side to assignment
\end_layout

\end_inset


\end_layout

\begin_layout Standard
In order to protect our function's calculations, we are urged to fully write
 out the symbols TRUE and FALSE inside functions.
 This way, users cannot cause damage.
 
\end_layout

\begin_layout Standard
Another danger we need to be concerned about is that our functions might
 have undefined variables in them.
 When R encounters these undefined variables, the lexical scoping process
 looks outward for values.
 It may find something we don't expect.
 Another danger is that a function seems to work right when we practice
 it in our session, but another user gets an error because something in
 our workspace is missing from theirs.
 The lexical scope can be convenient, but it is also dangerous.
\end_layout

\begin_layout Standard
Here the example function relies on variables 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
y
\end_layout

\end_inset

 and 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
z
\end_layout

\end_inset

 that are not passed in as arguments.
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

x <- c(1, 2, 3, 4)
\end_layout

\begin_layout Plain Layout

y <- c(8, 9, 10, 11)
\end_layout

\begin_layout Plain Layout

z <- c(1, 1, 2, 2)
\end_layout

\begin_layout Plain Layout

plotme <- function(x){
\end_layout

\begin_layout Plain Layout

    plot(x, y, col = z)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

plotme(x)
\end_layout

\end_inset


\end_layout

\begin_layout Standard
That lets the function go and find 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
y
\end_layout

\end_inset

 and 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
z
\end_layout

\end_inset

.
 This will run, but it is pretty risky.
 It depends on R's willingness to reach outside the boundaries of the function
 to find 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
y
\end_layout

\end_inset

, and 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
z
\end_layout

\end_inset

.
 If I have inadvertently altered 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
y
\end_layout

\end_inset

 in the workspace, this will end badly.
\end_layout

\begin_layout Standard
If I'm writing a function for somebody else to use, as in a package, I believe
 the function should to NOT rely on variables from the environment.
 I want to prevent R from filling in the gaps for users.
 We'd rather give the user an error 
\begin_inset Quotes eld
\end_inset

variable not found
\begin_inset Quotes erd
\end_inset

 than an erroneous calculation that 
\begin_inset Quotes eld
\end_inset

seems
\begin_inset Quotes erd
\end_inset

 adequate.
 The best case scenario is that 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
y
\end_layout

\end_inset

 and 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
z
\end_layout

\end_inset

 do not exist in the workspace, so the user will receive an error message:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout


\backslash
begin{Sinput}
\end_layout

\begin_layout Plain Layout

> plotme(x)
\end_layout

\begin_layout Plain Layout


\backslash
end{Sinput}
\end_layout

\begin_layout Plain Layout


\backslash
begin{Schunk}
\end_layout

\begin_layout Plain Layout

   
\backslash
begin{Soutput}
\end_layout

\begin_layout Plain Layout

Error in xy.coords(x, y, xlabel, ylabel, log) : object 'y' not found
\end_layout

\begin_layout Plain Layout

  
\backslash
end{Soutput}
\end_layout

\begin_layout Plain Layout


\backslash
end{Schunk}
\end_layout

\end_inset


\end_layout

\begin_layout Standard
The worst case scenario is that the user has some other variables 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
y
\end_layout

\end_inset

 and z
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout

\end_layout

\end_inset

 sitting about in the workspace.
 Those 
\begin_inset Quotes eld
\end_inset

found
\begin_inset Quotes erd
\end_inset

 variables are put to use with a completely unintentional result.
 
\end_layout

\begin_layout Standard
As a first step toward fixing this, I propose:
\end_layout

\begin_layout Quote
Every piece of input upon which we rely should be named in the list of arguments.
 
\end_layout

\begin_layout Standard
If we define the function as follows,
\end_layout

\begin_layout Standard
\begin_inset listings
inline false
status open

\begin_layout Plain Layout

plotme <- function(x, y, z){
\end_layout

\begin_layout Plain Layout

    plot(x, y, col = z)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\end_inset


\end_layout

\begin_layout Standard
the user's use of 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
plotme(x)
\end_layout

\end_inset

 will result in the error
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout


\backslash
begin{Schunk}
\end_layout

\begin_layout Plain Layout

   
\backslash
begin{Soutput}
\end_layout

\begin_layout Plain Layout

Error in xy.coords(x, y, xlabel, ylabel, log) :
\end_layout

\begin_layout Plain Layout

    argument "y" is missing, with no default
\end_layout

\begin_layout Plain Layout

   
\backslash
end{Soutput}
\end_layout

\begin_layout Plain Layout


\backslash
end{Schunk}
\end_layout

\end_inset

Naming all of the arguments effectively protects the function against the
 accidental importation of data.
 
\end_layout

\begin_layout Standard
There's a function called 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
checkUsage()
\end_layout

\end_inset

 in the 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
codetools
\end_layout

\end_inset

 package that can help check functions for reliance on global variables.
 First, we'll make sure the workspace is clean by removing 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
x
\end_layout

\end_inset

, 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
y
\end_layout

\end_inset

, and 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
z
\end_layout

\end_inset

.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout


\backslash
begin{Schunk}
\end_layout

\begin_layout Plain Layout

   
\backslash
begin{Soutput}
\end_layout

\begin_layout Plain Layout

> rm(x, y, z)
\end_layout

\begin_layout Plain Layout

> library(codetools) 
\end_layout

\begin_layout Plain Layout

> checkUsage(plotme) 
\end_layout

\begin_layout Plain Layout

<anonymous>: no visible binding for global variable 'y' (:2) 
\end_layout

\begin_layout Plain Layout

<anonymous>: no visible binding for global variable 'z' (:2)
\end_layout

\begin_layout Plain Layout

   
\backslash
end{Soutput}
\end_layout

\begin_layout Plain Layout


\backslash
end{Schunk}
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Note that, if the variables 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
x
\end_layout

\end_inset

, 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
y
\end_layout

\end_inset

, an 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
z
\end_layout

\end_inset

 exist in the user workspace, they are global and 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
checkUsage
\end_layout

\end_inset

 will not offer a warning about them.
 Hence, it is very important to run 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
checkUsage()
\end_layout

\end_inset

 after cleaning up the workspace.
 
\end_layout

\begin_layout Standard
checkUsage() will also offer warnings about unused variables.
 This can be helpful in cleaning up a function.
\end_layout

\begin_layout Subsection
Check argument values.
\end_layout

\begin_layout Standard
We want users to provide input arguments for all information that the calculatio
ns will rely upon.
 The next step is to check their inputs to make sure they are reasonable.
 
\end_layout

\begin_layout Standard
In some cases this is very easy.
 If we want the user to supply a data.frame, we can stop when the user provides
 something else.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

plotme <- function(x, y, data, ...){
\end_layout

\begin_layout Plain Layout

    if(missing(data) | !is.data.frame(data)) 
\end_layout

\begin_layout Plain Layout

        stop(paste0("plotme: the object you supplied as data: '", 
\end_layout

\begin_layout Plain Layout

        deparse(substitute(data)) , "' is not a data.frame"))
\end_layout

\begin_layout Plain Layout

    plot(as.formula(paste(y,  "~",  x, collapse=
\begin_inset Quotes erd
\end_inset

 
\begin_inset Quotes eld
\end_inset

)), data = data, ...)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

myx <- rnorm(10)
\end_layout

\begin_layout Plain Layout

myy <- rnorm(10)
\end_layout

\begin_layout Plain Layout

dat <- data.frame(myx, myy)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
This works properly
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<eval=F>>=
\end_layout

\begin_layout Plain Layout

plotme("myx", "myy", data = dat)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
However, if the user supplies something else where data ought to be, an
 error is returned.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout


\backslash
begin{Sinput}
\end_layout

\begin_layout Plain Layout

plotme("myx", "myy", rnorm(10))
\end_layout

\begin_layout Plain Layout


\backslash
end{Sinput}
\end_layout

\begin_layout Plain Layout


\backslash
begin{Soutput}
\end_layout

\begin_layout Plain Layout

Error in plotme("myx", "myy", rnorm(10)) :
\end_layout

\begin_layout Plain Layout

  plotme: the object you supplied as data: 'rnorm(10)' is not a data.frame
\end_layout

\begin_layout Plain Layout


\backslash
end{Soutput}
\end_layout

\end_inset


\end_layout

\begin_layout Standard
The main point here is that if we definitely know what we expect the user
 to supply, then we can add a filter that checks the input's type.
 That's what is.character, is.vector, is.integer, and so forth are intended
 for.
 (In an R session, type 
\begin_inset Quotes eld
\end_inset

is
\begin_inset Quotes erd
\end_inset

 and then hit the TAB key a couple of times.
 You'll see all the completions.
\end_layout

\begin_layout Standard
The problem is not so easy to manage when we can't be sure what the argument
 type must be.
 Sometimes, it appears the best we can do is pass through what the users
 give us and hope R can make sense out of it.
 I've wrestled with R's flexibility for the naming of colors.
 Suppose our plotme() function displays x and y, and we allow the user to
 specify colors for the points.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<>>=
\end_layout

\begin_layout Plain Layout

plotme <- function(x, y, z){
\end_layout

\begin_layout Plain Layout

    plot(x, y, col = z)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

myx <- rnorm(10)
\end_layout

\begin_layout Plain Layout

myy <- rnorm(10)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
R colors can be supplied in many formats, as integers, character strings,
 or more elaborate HTML-style color designators.
 Any of these will work.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<eval=F>>=
\end_layout

\begin_layout Plain Layout

mycol <- 1:10
\end_layout

\begin_layout Plain Layout

plotme(myx, myy, z = mycol)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<eval=F>>=
\end_layout

\begin_layout Plain Layout

mycol <- rainbow(10)
\end_layout

\begin_layout Plain Layout

plotme(myx, myy, z = mycol)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<eval=F>>=
\end_layout

\begin_layout Plain Layout

mycol <- gray.colors(10)
\end_layout

\begin_layout Plain Layout

plotme(myx, myy, z = mycol)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
R does not throw an error if the user runs this, but the result is not what
 we wanted, probably.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<eval=F>>=
\end_layout

\begin_layout Plain Layout

mycol <- rnorm(10)
\end_layout

\begin_layout Plain Layout

plotme(myx, myy, z = mycol)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Suppose the user's code ends up supplying a NULL value for 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
z
\end_layout

\end_inset

, as in 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
plotme(x, y, z = NULL)
\end_layout

\end_inset

.
 They would not do that on purpose, but it might be an accident.
 If 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
z
\end_layout

\end_inset

 is calculated in their code and something has gone wrong.
 To protect against that, we find this idiom is used in the R source code
 quite often:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<eval=F>>=
\end_layout

\begin_layout Plain Layout

plotme <- function(x, y, z){
\end_layout

\begin_layout Plain Layout

    if (missing(z) | is.null(z)) z <- rep(2, length(x))   
\end_layout

\begin_layout Plain Layout

    plot(x, y, col = z)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
If 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
z
\end_layout

\end_inset

 is either not supplied by the user's command, or if the user's command
 explicitly sets it to NULL, then we'll fabricate 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
z
\end_layout

\end_inset

.
\end_layout

\begin_layout Subsection
Design the function so that it runs with a minimum number of arguments.
\end_layout

\begin_layout Standard
Take a look at the most commonly used functions in R, such as lm() or plot.defaul
t().
 These functions allow a great many arguments, but they will deliver what
 the users minimally need if the they run
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<eval=F>>=
\end_layout

\begin_layout Plain Layout

m1 <- lm(y ~ x, data = dat)
\end_layout

\begin_layout Plain Layout

plot(y ~ x, data = dat)
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
Put the arguments that users will use most often at the front of the argument
 list, and then design the function so that it will work even if all of
 the other arguments are not included.
 There are two elements in making this work.
\end_layout

\begin_layout Subsubsection
Specify defaults
\end_layout

\begin_layout Standard
A graph can use any color scheme, but we might put in something colorful
 for users who like a little zest in life.
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<eval=F>>=
\end_layout

\begin_layout Plain Layout

plotme <- function(x, y, z = rainbow(length(x))){     
\end_layout

\begin_layout Plain Layout

    plot(x, y, col = z)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

plotme(x = rnorm(100), y = rnorm(100))
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
We could as well have put the rainbow call inside the function if we want
 to keep a cleaner function declaration.
 
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<eval=F>>=
\end_layout

\begin_layout Plain Layout

plotme <- function(x, y, z){     
\end_layout

\begin_layout Plain Layout

  if(missing(z)) mycol <- rainbow(length(x))
\end_layout

\begin_layout Plain Layout

  plot(x, y, col = mycol)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

plotme(x = rnorm(100), y = rnorm(100))
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
It seems to me that the R source itself tends to have more elaborate specificati
ons of defaults within the declaration, rather than inside the function.
\end_layout

\begin_layout Standard
In the R source code, I noticed a peculiar-looking example in which an argument'
s default depends on a function that is within the function itself.
 Observe that this runs fine:
\end_layout

\begin_layout Standard
\begin_inset ERT
status open

\begin_layout Plain Layout

<<eval=F>>=
\end_layout

\begin_layout Plain Layout

plotme <- function(x, y, z = getAColor(length(x)))
\end_layout

\begin_layout Plain Layout

{
\end_layout

\begin_layout Plain Layout

    getAColor <- function(n){
\end_layout

\begin_layout Plain Layout

             gray.colors(n)
\end_layout

\begin_layout Plain Layout

    }
\end_layout

\begin_layout Plain Layout

    plot(x, y, col = z, cex = 5)
\end_layout

\begin_layout Plain Layout

}
\end_layout

\begin_layout Plain Layout

plotme(rnorm(20), rnorm(20))
\end_layout

\begin_layout Plain Layout

@
\end_layout

\end_inset


\end_layout

\begin_layout Standard
That was startling to me because the nested function, 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
getAColor
\end_layout

\end_inset

, does not exist outside the function, and yet it can be used in the definition
 of a default.
 I merely promise that 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
getAColor
\end_layout

\end_inset

 will exist when the value of 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
z
\end_layout

\end_inset

 is needed and all is well.
 
\end_layout

\begin_layout Subsubsection
Extract or construct what else is needed from the user input
\end_layout

\begin_layout Standard
We can deduce information from the arguments that are passed in, we can
 eliminate the need for the user to pass in other arguments.
 We would never need to require both arguments x and xlab in the plot function,
 for example.
 xlab is optional because, if the user does not supply it, then deparse(substitu
te()) can find something to use as a label.
 The 2010 version of plotSlopes in rockchalk required the user to pass through
 many parameters that (I've since learned) can be deduced from the other
 arguments.
\end_layout

\begin_layout Standard
A key element in this is getting an understanding of the information that
 comes in with a standard R object.
 Quite a few–almost all–functions that generate interesting objects in R
 provide, as a part of their output, a copy of the call that ran the function.
 Inside our functions, we can inspect that call argument to see what the
 users ran, and from that we can often deduce what we need without requiring
 users to supply a lot of information.
 
\end_layout

\begin_layout Subsection
Return values versus attributes
\end_layout

\begin_layout Standard
If you review the R regression functions, like lm() or glm(), you notice
 that they build a list of things and pass it back to the user.
 That is the most obvious way to return information.
\end_layout

\begin_layout Standard
There is another way, however, which is a little interesting.
 One can mark an attribute on a return object.
 The R usage of attributes comes to mind at this point because, when we
 are scanning for inputs, we may need to inspect not only their values,
 but also their attributes.
 The most commonly inspected attribute, of course, is the class of the argument.
 So, if we are writing a package and we need to make sure that the objects
 being passed around among functions are correct for the purpose, then the
 object attributes are a very useful tool.
\end_layout

\begin_layout Standard
I don't want to write a lot about this so as to display my ignorance, but
 I would point user to 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
pctable()
\end_layout

\end_inset

 as an example of a rockchalk function that uses both a return list and
 attributes to get the job done.
 Maybe I'll fill in this example at a later time, once I figure out the
 most direct way to explain it.
\end_layout

\begin_layout Standard
The only problem I find with attributes is that the printing functions for
 R objects generally 
\begin_inset Quotes eld
\end_inset

splat out
\begin_inset Quotes erd
\end_inset

 the attributes when we don't want them.
 If one puts attributes on an object, then the default printer will show
 them.
 I've not learned all of the ins-and-outs of preventing that, but in 2015
 I became aware of it and learned that one way to deal with it can be found
 in the R source code for the method 
\begin_inset Flex Code
status collapsed

\begin_layout Plain Layout
print.table()
\end_layout

\end_inset

.
 
\end_layout

\begin_layout Section
Do This, Not That (Stub) 
\end_layout

\begin_layout Standard
R novices sometimes use Google to search for R advice and they find it,
 good or bad.
 They may find their way to the r-help email list, where advice is generally
 good, or to the StackOverflow pages for R, which may be better.
 A lot of advice is offered by people like me, who may have good intentions,
 but are simply not qualified to offer advice.
 
\end_layout

\begin_layout Standard
One of the few bits of advice that seems to grab widespread support is that
 
\begin_inset Quotes eld
\end_inset

for loops are bad.
\begin_inset Quotes erd
\end_inset

 One can write an lapply statement in one line, while a for loop can take
 3 lines.
 The code is shorter, but it won't necessarily run more quickly.
 I recall being jarred by this revelation in John Chambers's book, 
\emph on
Software for Data Analysis
\emph default
.
 The members of the apply family (apply, lapply, sapply, etc) can make for
 more readable code, but they aren't always faster.
 
\begin_inset Quotes eld
\end_inset

However, none of the apply mechanisms changes the number of times the supplied
 function is called, so serious improvements will be limited to iterating
 simple calculations many times.
 Otherwise, the n evaluations of the function can be expected to be the
 dominant fraction of the computation
\begin_inset Quotes erd
\end_inset


\begin_inset CommandInset citation
LatexCommand citep
after "213"
key "chambers_software_2008"
literal "true"

\end_inset

.
\end_layout

\begin_layout Standard
Todo: insert discussion of stackListItems-001.
\end_layout

\begin_layout Standard
Insert alternative methods of measuring executation time and measuring performan
ce
\end_layout

\begin_layout Standard
Balance time spent optimizing code versus time spent running program.
\end_layout

\begin_layout Section
Suggested Chores
\end_layout

\begin_layout Standard
I suggest the would be programmer should take on some basic challenges.
 
\end_layout

\begin_layout Enumerate
Try to create a generic function and several methods to handle classes of
 various types.
 If the term 
\begin_inset Quotes eld
\end_inset

generic function
\begin_inset Quotes erd
\end_inset

 and 
\begin_inset Quotes eld
\end_inset

method
\begin_inset Quotes erd
\end_inset

 cause disorientation, that means the reader is a user, not a programmer
 yet.
 
\end_layout

\begin_layout Enumerate
Consider developing a routine (or package) for statistical estimation or
 presentation.
 Find several R packages and compare the R code in them.
 Let me know if you agree with me about these points.
\end_layout

\begin_layout Itemize
Good code is compartmentalized.
 Separate pieces of work are handled by separated functions and results
 are returned in a well organized way.
\end_layout

\begin_layout Itemize
Functions should not be HUGE.
 
\begin_inset Separator latexpar
\end_inset


\end_layout

\begin_deeper
\begin_layout Standard
The components of a project should be small enough so that we can comprehend
 them.
 Generally speaking, if we are reading code and we come to a line that uses
 a variable that we cannot find on the screen, that's a problem.
 I used to correspond with a programmer at the University of Michigan who
 said he began to feel uncomfortable when a function filled up the entire
 terminal screen.
 
\end_layout

\end_deeper
\begin_layout Itemize
People who copy and paste sections over and over in order to handle slightly
 different cases are causing trouble for themselves and others.
 They should think harder on ways to separate that work into re-usable functions.
 
\end_layout

\begin_layout Standard
\begin_inset CommandInset bibtex
LatexCommand bibtex
bibfiles "rockchalk"
options "chicago"

\end_inset


\end_layout

\end_body
\end_document
