\input texinfo
@c %**start of header
@setfilename R-FAQ.info
@settitle R FAQ
@setchapternewpage on
@set FAQ-YEAR 2001
@set FAQ-VERSION 1.3-20, 2001-08-31
@set REL-VERSION 1.3.1
@c %**end of header

@dircategory Programming
@direntry
* R FAQ: (R-FAQ).               The R statistical system FAQ.
@end direntry

@finalout

@macro SPLUS{}
@sc{S-Plus}
@end macro

@macro HTML{}
@acronym{HTML}
@end macro

@macro FORTRAN{}
FORTRAN
@end macro

@titlepage
@title R @acronym{FAQ}
@subtitle Frequently Asked Questions on R
@subtitle Version @value{FAQ-VERSION}
@author Kurt Hornik
@end titlepage

@ifinfo
@c We do not really see this in info, but in plain text output.
R FAQ                            @*
Frequently Asked Questions on R  @*
Version @value{FAQ-VERSION}      @*
Kurt Hornik                      @*

@sp 2
@end ifinfo

@ifnothtml
@contents
@end ifnothtml

@ifnottex
@node Top, Introduction, (dir), (dir)
@top R FAQ
@ifhtml
@html
<h2>Frequently Asked Questions on R</h2>
<h2>Version @value{FAQ-VERSION}</h2>
<address>Kurt Hornik</address>
<p><p><hr><p>
@end html
@end ifhtml
@end ifnottex

@menu
* Introduction::                
* R Basics::                    
* R and S::                     
* R Web Interfaces::            
* R Add-On Packages::           
* R and Emacs::                 
* R Miscellanea::               
* R Programming::               
* R Bugs::                      
* Acknowledgments::             
@end menu

@node Introduction, R Basics, Top, Top
@chapter Introduction

This document contains answers to some of the most frequently asked
questions about R.

@menu
* Legalese::                    
* Obtaining this document::     
* Citing this document::        
* Notation::                    
* Feedback::                    
@end menu

@node Legalese, Obtaining this document, Introduction, Introduction
@section Legalese

This document is free software; you can redistribute it and/or modify it
under the terms of the @acronym{GNU} General Public License as published
by the Free Software Foundation; either version 2, or (at your option)
any later version.

This document is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
@acronym{GNU} General Public License for more details.

A copy of the @acronym{GNU} General Public License is available via WWW
at

@display
@uref{http://www.gnu.org/copyleft/gpl.html}.
@end display

@noindent
You can also obtain it by writing to the Free Software Foundation, Inc.,
59 Temple Place --- Suite 330, Boston, MA 02111-1307, USA.

@node Obtaining this document, Citing this document, Legalese, Introduction
@section Obtaining this document

The latest version of this document is always available from

@display
@uref{http://www.ci.tuwien.ac.at/~hornik/R/}
@end display

From there, you can obtain versions converted to
@uref{http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.txt,, plain
@acronym{ASCII} text},
@uref{http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.dvi.gz,, DVI},
@uref{http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.info.gz,, @acronym{GNU}
info}, @uref{http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html,, @HTML{}},
@uref{http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.pdf,, PDF},
@uref{http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.ps.gz,, PostScript} as
well as the @uref{http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.texi,,
Texinfo source} used for creating all these formats using the
@uref{http://texinfo.org/, @acronym{GNU} Texinfo system}.

You can also obtain the R @acronym{FAQ} from the @file{doc/FAQ}
subdirectory of a @acronym{CRAN} site (@pxref{What is CRAN?}).

@node Citing this document, Notation, Obtaining this document, Introduction
@section Citing this document

In publications, please refer to this @acronym{FAQ} as Hornik
(@value{FAQ-YEAR}), ``The R @acronym{FAQ}'' and give the above,
@emph{official} @acronym{URL}.

@node Notation, Feedback, Citing this document, Introduction
@section Notation

Everything should be pretty standard.  @samp{R>} is used for the R
prompt, and a @samp{$} for the shell prompt (where applicable).

@node Feedback,  , Notation, Introduction
@section Feedback

Feedback is of course most welcome.

In particular, note that I do not have access to Windows or Mac systems.
Features specific to the Windows and Mac OS ports of R are described in
the @uref{http://www.stats.ox.ac.uk/pub/R/rw-FAQ.html, ``R for Windows
@acronym{FAQ}''} and the
@uref{http://www.eco-dip.unimi.it/R/rmac-FAQ.html, ``R for Macintosh
@acronym{FAQ}/DOC''}.  If you have information on Mac or Windows systems
that you think should be added to this document, please let me know.

@c <FIXME>
@c Should we maybe have direct links inside the R tree to the various
@c rw-FAQ versions?
@c </FIXME>

@node R Basics, R and S, Introduction, Top
@chapter R Basics

@menu
* What is R?::                  
* What machines does R run on?::  
* What is the current version of R?::  
* How can R be obtained?::      
* How can R be installed?::     
* Are there Unix binaries for R?::  
* What documentation exists for R?::  
* Citing R::                    
* What mailing lists exist for R?::  
* What is CRAN?::               
@end menu

@node What is R?, What machines does R run on?, R Basics, R Basics
@section What is R?

R is a system for statistical computation and graphics.  It consists of
a language plus a run-time environment with graphics, a debugger, access
to certain system functions, and the ability to run programs stored in
script files.

The design of R has been heavily influenced by two existing languages:
Becker, Chambers & Wilks' S (@pxref{What is S?}) and Sussman's
@uref{http://www.cs.indiana.edu/scheme-repository/home.html, Scheme}.
Whereas the resulting language is very similar in appearance to S, the
underlying implementation and semantics are derived from Scheme.
@xref{What are the differences between R and S?}, for further details.

The core of R is an interpreted computer language which allows branching
and looping as well as modular programming using functions.  Most of the
user-visible functions in R are written in R.  It is possible for the
user to interface to procedures written in the C, C++, or FORTRAN
languages for efficiency.  The R distribution contains functionality for
a large number of statistical procedures.  Among these are: linear and
generalized linear models, nonlinear regression models, time series
analysis, classical parametric and nonparametric tests, clustering and
smoothing.  There is also a large set of functions which provide a
flexible graphical environment for creating various kinds of data
presentations.  Additional modules (``add-on packages'') are available
for a variety of specific purposes (@pxref{R Add-On Packages}).

R was initially written by @email{Ross.Ihaka@@r-project.org, Ross Ihaka}
and @email{Robert.Gentleman@@r-project.org, Robert Gentleman} at the
Department of Statistics of the University of Auckland in Auckland, New
Zealand.  In addition, a large group of individuals has contributed to R
by sending code and bug reports.

Since mid-1997 there has been a core group (the ``R Core Team'') who can
modify the R source code CVS archive.  The group currently consists of
Doug Bates, John Chambers, Peter Dalgaard, Robert Gentleman, Kurt
Hornik, Stefano Iacus, Ross Ihaka, Friedrich Leisch, Thomas Lumley,
Martin Maechler, Guido Masarotto, Paul Murrell, Brian Ripley, Duncan
Temple Lang, and Luke Tierney.

R has a home page at @uref{http://www.r-project.org/}.  It is free
software distributed under a @acronym{GNU}-style copyleft, and an
official part of the @acronym{GNU} project (``@acronym{GNU} S'').

@node What machines does R run on?, What is the current version of R?, What is R?, R Basics
@section What machines does R run on?

R is being developed for the Unix, Windows and Mac families of operating
systems.

The current version of R will configure and build under a number of
common Unix platforms including i386-freebsd, i386-linux-gnu,
i386-sun-solaris, powerpc-linux-gnu, powerpc-apple-darwin,
mips-sgi-irix, alpha-linux-gnu, alpha-dec-osf4, rs6000-ibm-aix,
hppa-hp-hpux, sparc-linux-gnu, and sparc-sun-solaris.

@c and according to @email{jlindsey@@luc.ac.be, Jim Lindsey} also on
@c Mac, Amiga and Atari under m68k-linux.

If you know about other platforms, please drop us a note.

@node What is the current version of R?, How can R be obtained?, What machines does R run on?, R Basics
@section What is the current version of R?
 
The current released version is @value{REL-VERSION}.  Conforming to this
`major.minor.patchlevel' numbering scheme, there are three development
versions of R, working towards the next patch (`r-patched'), minor
(`r-devel'), and major (`r-ng') releases of R, respectively.  Version
r-patched is for bug fixes mostly.  New features are typically
introduced in r-devel.  Version r-ng will eventually become the next
generation of R.

@node How can R be obtained?, How can R be installed?, What is the current version of R?, R Basics
@section How can R be obtained?

Sources, binaries and documentation for R can be obtained via
@acronym{CRAN}, the ``Comprehensive R Archive Network'' (see @ref{What
is CRAN?}).

Sources are also available via anonymous rsync.  Use

@smallexample
rsync -rC rsync.r-project.org::@var{module} R
@end smallexample

@noindent
to create a copy of the source tree specified by @var{module} in the
subdirectory @file{R} of the current directory, where @var{module}
specifies one of the four existing flavors of the R sources, and can be
one of @samp{r-release} (current released version), @samp{r-patched}
(patched released version), and @samp{r-devel} (development version,
less stable), and @samp{r-ng} (next generation, unstable).  The rsync
trees are created directly from the master CVS archive and are updated
hourly.  The @option{-C} option in the @command{rsync} command is to
cause it to skip the CVS directories.  Further information on
@command{rsync} is available at @uref{http://rsync.samba.org/rsync/}.

@node How can R be installed?, Are there Unix binaries for R?, How can R be obtained?, R Basics
@section How can R be installed?

@menu
* How can R be installed (Unix)::  
* How can R be installed (Windows)::  
* How can R be installed (Macintosh)::  
@end menu

@node How can R be installed (Unix), How can R be installed (Windows), How can R be installed?, How can R be installed?
@subsection How can R be installed (Unix)

If binaries are available for your platform (see @ref{Are there Unix
binaries for R?}), you can use these, following the instructions that
come with them.

Otherwise, you can compile and install R yourself, which can be done
very easily under a number of common Unix platforms (see @ref{What
machines does R run on?}).  The file @file{INSTALL} that comes with the
R distribution contains a brief introduction, and the ``R Installation
and Administration'' guide (@pxref{What documentation exists for R?})
has full details.

Note that you need a @FORTRAN{} compiler or @command{f2c} in addition to
a C compiler to build R.  Also, you need Perl version 5 to build the R
object documentations.  (If this is not available on your system, you
can obtain a PDF version of the object reference manual via
@acronym{CRAN}.)

In the simplest case, untar the R source code, change to the directory
thus created, and issue the following commands (at the shell prompt):

@smallexample
$ ./configure
$ make
@end smallexample

If these commands execute successfully, the R binary and a shell script
font-end called @file{R} are created and copied to the @file{bin}
directory.  You can copy the script to a place where users can invoke
it, for example to @file{/usr/local/bin}.  In addition, plain text help
pages as well as @HTML{} and La@TeX{} versions of the documentation are
built.

Use @kbd{make dvi} to create DVI versions of the R manuals, such as
@file{refman.dvi} (an R object reference index) and @file{R-exts.dvi},
the ``R Extension Writers Guide'', in the @file{doc/manual}
subdirectory.  These files can be previewed and printed using standard
programs such as @command{xdvi} and @command{dvips}.  You can also use
@kbd{make pdf} to build PDF (Portable Document Format) version of the
manuals, and view these using e.g.@: Acrobat.  Manuals written in the
@acronym{GNU} Texinfo system can also be converted to info files
suitable for reading online with Emacs or stand-alone @acronym{GNU}
Info; use @kbd{make info} to create these versions (note that this
requires @command{makeinfo} version 4).

Finally, use @kbd{make check} to find out whether your R system works
correctly.

You can also perform a ``system-wide'' installation using @kbd{make
install}.  By default, this will install to the following directories:

@table @file
@item $@{prefix@}/bin
the front-end shell script
@item $@{prefix@}/man/man1
the man page
@item $@{prefix@}/lib/R
all the rest (libraries, on-line help system, @dots{}).  This is the ``R
Home Directory'' (@env{R_HOME}) of the installed system.
@end table

@noindent
In the above, @code{prefix} is determined during configuration
(typically @file{/usr/local}) and can be set by running
@command{configure} with the option

@smallexample
$ ./configure --prefix=/where/you/want/R/to/go
@end smallexample

@noindent
(E.g., the R executable will then be installed into
@file{/where/you/want/R/to/go/bin}.)

To install DVI, info and PDF versions of the manuals, use @kbd{make
install-dvi}, @kbd{make install-info} and @kbd{make install-pdf},
respectively.

@node How can R be installed (Windows), How can R be installed (Macintosh), How can R be installed (Unix), How can R be installed?
@subsection How can R be installed (Windows)

The @file{bin/windows} directory of a @acronym{CRAN} site contains
binaries for a base distribution and a large number of add-on packages
from @acronym{CRAN} to run on Windows 95, 98, NT4, 2000 and ME (at
least) on Intel and clones (but not on other platforms).  The Windows
version of R was created by Robert Gentleman, and is now being developed
and maintained by @email{Guido.Masarotto@@r-project.org, Guido
Masarotto} and @email{Brian.Ripley@@r-project.org, Brian D. Ripley}.

@c Note that when uncompressing the zip files, the pkunzip program needs to
@c be invoked with the @samp{-D} flag to create subdirectories.  Also, be
@c aware that some decompression programs do not preserve long file names
@c properly.

For most installations the installer @command{rwinst.exe} will be the
easiest tool to use.

See the @uref{http://www.stats.ox.ac.uk/pub/R/rw-FAQ.html, ``R for
Windows @acronym{FAQ}''} for more details.

@node How can R be installed (Macintosh),  , How can R be installed (Windows), How can R be installed?
@subsection How can R be installed (Macintosh)

The @file{bin/macos} directory of a @acronym{CRAN} site contains
bin-hexed (@file{hqx}) and stuffit (@file{sit}) archives for a base
distribution and a large number of add-on packages to run under MacOS
8.6 to MacOS 9.1 or MacOS X natively.  The Mac version of R and the Mac
binaries are maintained by
@c @email{stefano.iacus@@unimi.it, Stefano Iacus}.
@email{Stefano.Iacus@@r-project.org, Stefano Iacus}.

The @uref{http://www.eco-dip.unimi.it/R/rmac-FAQ.html, ``R for Macintosh
@acronym{FAQ}/DOC''} has more details.

Binaries of base distributions for MacOS X (Darwin) with X11 are made
available by @email{deleeuw@@stat.ucla.edu, Jan de Leeuw} in the
@file{bin/macosx} directory of a @acronym{CRAN} site.
@c @uref{http://www.stat.ucla.edu/~deleeuw/R/}.

@node Are there Unix binaries for R?, What documentation exists for R?, How can R be installed?, R Basics
@section Are there Unix binaries for R?

@c Linux binaries as of 2001-07-11:
@c
@c debian   2.2 i386  1.3.0  Doug Bates <bates@stat.wisc.edu>
@c          2.3 i386  1.3.0  Doug Bates <bates@stat.wisc.edu>
@c linuxppc 5.0 ppc   1.3.0  Alex Buerkle <buerkle@hawaii.edu>
@c mandrake 7.x i386  1.3.0  Maximino Ameneiro Gomez <maximino.ameneiro@metropoli2000.com>
@c          8.0 i386  1.3.0  Michele Alzetta <mikalzet@libero.it>
@c redhat   6.x alpha 1.2.2  Naoki Takebayashi <ntakebay@bio.indiana.edu>
@c              i386  1.2.3  Martyn Plummer <plummer@iarc.fr>
@c          7.x alpha 1.3.0  Naoki Takebayashi <ntakebay@bio.indiana.edu>
@c              i386  1.3.0  Martyn Plummer <plummer@iarc.fr>
@c suse     7.2 i386  1.3.0  A Gebhardt <albrecht.gebhardt@uni-klu.ac.at>

The @file{bin/linux} directory of a @acronym{CRAN} site contains Debian
2.2/2.3 packages for the i386 platform (now part of the Debian
distribution and maintained by Doug Bates), Red Hat 6.x/7.x packages for
the alpha and i386 platforms (maintained by Naoki Takebayashi and Martyn
Plummer, respectively), SuSE 7.2 i386 packages by Albrecht Gebhardt,
Mandrake 8.0 and 7.2 i386 packages by Michele Alzetta and Maximino
Ameneiro Gomez, and LinuxPPC 5.0 RPMs by Alex Buerkle.

The Debian packages can be accessed through APT, the Debian package
maintenance tool.  Simply add the line

@smallexample
deb http://cran.r-project.org/bin/linux/debian @var{distribution} main
@end smallexample

@noindent
(where @var{distribution} is either @samp{stable} or @samp{unstable};
feel free to use a @acronym{CRAN} mirror instead of the master) to the
file @file{/etc/apt/sources.list}.  Once you have added that line the
programs @command{apt-get}, @command{apt-cache}, and @command{dselect}
(using the apt access method) will automatically detect and install
updates of the R packages.

The @file{bin/osf} directory of a @acronym{CRAN} site contains RPMs by
Albrecht Gebhardt for alpha systems running Alpha Unix (OSF/Tru64).

@c There are also `tar' distributions for NEXTSTEP on the i386 and m68k
@c platforms in @file{bin/nextstep/i386} and @file{bin/nextstep/m68k},
@c created by Stephen Shiboski <steve@biostat.ucsf.edu>.

No other binary distributions have thus far been made publically
available.

@node What documentation exists for R?, Citing R, Are there Unix binaries for R?, R Basics
@section What documentation exists for R?

Online documentation for most of the functions and variables in R
exists, and can be printed on-screen by typing @kbd{help(@var{name})}
(or @kbd{?@var{name}}) at the R prompt, where @var{name} is the name of
the topic help is sought for.  (In the case of unary and binary
operators and control-flow special forms, the name may need to be be
quoted.)

This documentation can also be made available as one reference manual
for on-line reading in @HTML{} and PDF formats, and as hardcopy via
La@TeX{}, see @ref{How can R be installed?}.  An up-to-date @HTML{}
version is always available for web browsing at
@uref{http://stat.ethz.ch/R/manual/}.

The R distribution also comes with the following manuals.

@itemize @bullet
@item ``An Introduction to R'' (@file{R-intro})
includes information on data types, programming elements, statistical
modeling and graphics.  This document is based on the ``Notes on
@SPLUS{}'' by Bill Venables and David Smith.
@item ``Writing R Extensions'' (@file{R-exts})
currently describes the process of creating R add-on packages, writing R
documentation, R's system and foreign language interfaces, and the R
@acronym{API}.
@item ``R Data Import/Export'' (@file{R-data})
is a guide to importing and exporting data to and from R.
@item ``The R Language Definition'' (@file{R-lang}),
a first version of the ``Kernighan & Ritchie of R'', explains
evaluation, parsing, object oriented programming, computing on the
language, and so forth.
@item ``R Installation and Administration'' (@file{R-admin}).
@end itemize

In addition to material written specifically for R, documentation for
S/@SPLUS{} (see @ref{R and S}) can be used in combination with this
@acronym{FAQ} (@pxref{What are the differences between R and S?}).  We
recommend

@quotation
W. N. Venables and B. D. Ripley (1999), ``Modern Applied Statistics with
@SPLUS{}.  Third Edition''.  Springer, ISBN 0-387-98825-4.
@end quotation

@noindent
This has a home page at @uref{http://www.stats.ox.ac.uk/pub/MASS3/}
providing additional material, in particular ``R Complements'' which
describe how to use the book with R.  These complements contain both
descriptions of some of the differences between R and @SPLUS{}, and the
modifications needed to run the examples in the book.  Its companion is

@quotation
W. N. Venables and B. D. Ripley (2000), ``S Programming''.  Springer,
ISBN 0-387-98966-8.
@end quotation

@noindent
This provides an in-depth guide to writing software in the S language
which forms the basis of both the commercial @SPLUS{} and the Open
Source R data analysis software systems.  See
@uref{http://www.stats.ox.ac.uk/pub/MASS3/Sprog/} for more information.

More introductory books are

@quotation
P. Spector (1994), ``An introduction to S and @SPLUS{}'', Duxbury Press.

A. Krause and M. Olsen (1997), ``The Basics of S and @SPLUS{}'',
Springer.
@end quotation

The book

@quotation
J. C. Pinheiro and D. M. Bates (2000), ``Mixed-Effects Models in S and
@SPLUS{}'', Springer, ISBN 0-387-98957-0
@end quotation

@noindent
provides a comprehensive guide to the use of the @strong{nlme} package
for linear and nonlinear mixed-effects models.  This has a home page at
@uref{http://nlme.stat.wisc.edu/MEMSS/}.

As an example of how R can be used in teaching an advanced introductory
statistics course, see

@quotation
D. Nolan and T. Speed (2000), ``Stat Labs: Mathematical Statistics
Through Applications'', Springer Texts in Statistics, ISBN
0-387-98974-9
@end quotation

@noindent
This integrates theory of statistics with the practice of statistics
through a collection of case studies (``labs''), and uses R to analyze
the data.  More information can be found at
@uref{http://www.stat.Berkeley.EDU/users/statlabs/}.

Last, but not least, Ross' and Robert's experience in designing and
implementing R is described in Ihaka & Gentleman (1996), ``R: A Language
for Data Analysis and Graphics'',
@uref{http://www.amstat.org/publications/jcgs/, , @emph{Journal of
Computational and Graphical Statistics}}, @strong{5}, 299--314.
@xref{Citing R}.

An annotated bibliography (Bib@TeX{} format) of R-related publications
which includes most of the above references can be found at

@display
@uref{http://www.r-project.org/doc/bib/R.bib}
@end display

@node Citing R, What mailing lists exist for R?, What documentation exists for R?, R Basics
@section Citing R

To cite R in publications, use

@smallexample
@group
@@article@{,
  author =    @{Ross Ihaka and Robert Gentleman@},
  title =     @{R: A Language for Data Analysis and Graphics@},
  journal =   @{Journal of Computational and Graphical Statistics@},
  year =      1996,
  volume =    5,
  number =    3,
  pages =     @{299--314@}
@}
@end group
@end smallexample

@node What mailing lists exist for R?, What is CRAN?, Citing R, R Basics
@section What mailing lists exist for R?

Thanks to @email{Martin.Maechler@@r-project.org, Martin Maechler}, there
are three mailing lists devoted to R.

@table @code
@item r-announce
This list is for announcements about the development of R and the
availability of new code.
@item r-devel
This list is for discussions about the future of R and pre-testing of
new versions.  It is meant for those who maintain an active position in
the development of R.
@item r-help
The `main' R mailing list, for announcements about the development of R
and the availability of new code, questions and answers about problems
and solutions using R, enhancements and patches to the source code and
documentation of R, comparison and compatibility with S and @SPLUS{},
and for the posting of nice examples and benchmarks.
@end table

@noindent
Note that the r-announce list is gatewayed into r-help, so you don't
need to subscribe to both of them.

Send email to @email{r-help@@lists.r-project.org} to reach everyone on
the r-help mailing list.  To subscribe (or unsubscribe) to this list
send @samp{subscribe} (or @samp{unsubscribe}) in the @emph{body} of the
message (not in the subject!) to
@email{r-help-request@@lists.r-project.org}.  Information about the list
can be obtained by sending an email with @samp{info} as its contents to
@email{r-help-request@@lists.r-project.org}.

Subscription and posting to the other lists is done analogously, with
`r-help' replaced by `r-announce' and `r-devel', respectively.

It is recommended that you send mail to r-help rather than only to the R
Core developers (who are also subscribed to the list, of course).  This
may save them precious time they can use for constantly improving R, and
will typically also result in much quicker feedback for yourself.

Of course, in the case of bug reports it would be very helpful to have
code which reliably reproduces the problem.  Also, make sure that you
include information on the system and version of R being used.  See
@ref{R Bugs} for more details.

Archives of the above three mailing lists are made available on the net
in a monthly schedule via the @file{doc/html/mail.html} file in
@acronym{CRAN}.  Searchable archives of the lists are available via
@uref{http://www.ens.gu.edu.au/robertk/R/}.

The R Core Team can be reached at @email{r-core@@lists.r-project.org}
for comments and reports.

@node What is CRAN?,  , What mailing lists exist for R?, R Basics
@section What is @acronym{CRAN}?

The ``Comprehensive R Archive Network'' (@acronym{CRAN}) is a collection
of sites which carry identical material, consisting of the R
distribution(s), the contributed extensions, documentation for R, and
binaries.

The @acronym{CRAN} master site at TU Wien, Austria, can be found at the
@acronym{URL}

@quotation
@c @multitable @columnfractions .45 .30
@c @item
@uref{http://cran.r-project.org/}
@c @tab (Austria)
@c @end multitable
@end quotation

@noindent
@c (which is the same as @uref{http://cran.at.r-project.org/})
and is currently being mirrored daily at

@quotation
@multitable @columnfractions .40 .40
@item @uref{http://cran.at.r-project.org/}
@tab (TU Wien, Austria)
@item @uref{http://cran.au.r-project.org/}
@tab (PlanetMirror, Australia)
@item @uref{http://cran.ch.r-project.org/}
@tab (ETH Z@"urich, Switzerland)
@item @uref{http://cran.dk.r-project.org/}
@tab (SunSITE, Denmark)
@item @uref{http://cran.hu.r-project.org/}
@tab (Semmelweis U, Hungary)
@c @item @uref{http://cran.it.r-project.org/}
@c @tab (Italy)
@item @uref{http://cran.uk.r-project.org/}
@tab (U of Bristol, United Kingdom)
@item @uref{http://cran.us.r-project.org/}
@tab (U of Wisconsin, USA)
@item @uref{http://cran.za.r-project.org/}
@tab (Rhodes U, South Africa)
@end multitable
@end quotation

@noindent
Please use the @acronym{CRAN} site closest to you to reduce network
load.

From @acronym{CRAN}, you can obtain the latest official release of R,
daily snapshots of R (copies of the current CVS trees), as gzipped and
bzipped tar files, a wealth of additional contributed code, as well as
prebuilt binaries for various operating systems (Linux, Digital Unix,
and MS Windows).  @acronym{CRAN} also provides access to documentation
on R, existing mailing lists and the R Bug Tracking system.

To ``submit'' to @acronym{CRAN}, simply upload to
@uref{ftp://cran.r-project.org/incoming/} and send an email to
@email{wwwadmin@@cran.r-project.org}.

@quotation
@strong{Note:}  It is very important that you indicate the copyright
(license) information (@acronym{GPL}, @acronym{BSD}, Artistic, @dots{})
in your submission.
@end quotation

Please always use the @acronym{URL} of the master site when referring to
@acronym{CRAN}.

@node R and S, R Web Interfaces, R Basics, Top
@chapter R and S

@menu
* What is S?::                  
* What is S-PLUS?::             
* What are the differences between R and S?::  
* Is there anything R can do that S-PLUS cannot?::  
* What is R-plus?::             
@end menu

@node What is S?, What is S-PLUS?, R and S, R and S
@section What is S?

S is a very high level language and an environment for data analysis and
graphics.  In 1998, the Association for Computing Machinery
(@acronym{ACM}) presented its Software System Award to John M. Chambers,
the principal designer of S, for

@quotation
the S system, which has forever altered the way people analyze,
visualize, and manipulate data @dots{}

S is an elegant, widely accepted, and enduring software system, with
conceptual integrity, thanks to the insight, taste, and effort of John
Chambers.
@end quotation

The evolution of the S language is characterized by four books by John
Chambers and coauthors, which are also the primary references for S.

@itemize @bullet
@item
Richard A. Becker and John M. Chambers (1984), ``S.  An Interactive
Environment for Data Analysis and Graphics,'' Monterey: Wadsworth and
Brooks/Cole.

This is also referred to as the ``@emph{Brown Book}'', and of historical
interest only.

@item
Richard A. Becker, John M. Chambers and Allan R. Wilks (1988), ``The New
S Language,'' London: Chapman & Hall.

This book is often called the ``@emph{Blue Book}'', and introduced what
is now known as S version 2.

@item
John M. Chambers and Trevor J. Hastie (1992), ``Statistical Models in
S,''  London: Chapman & Hall.

This is also called the ``@emph{White Book}'', and introduced S version
3, which added structures to facilitate statistical modeling in S.

@item
John M. Chambers (1998), ``Programming with Data,'' New York: Springer,
ISBN 0-387-98503-4
(@url{http://cm.bell-labs.com/cm/ms/departments/sia/Sbook/}).

This ``@emph{Green Book}'' describes version 4 of S, a major revision of
S designed by John Chambers to improve its usefulness at every stage of
the programming process.
@end itemize

See @uref{http://cm.bell-labs.com/cm/ms/departments/sia/S/history.html}
for further information on ``Stages in the Evolution of S''.

There is a huge amount of user-contributed code for S, available at the
@uref{http://lib.stat.cmu.edu/S/, S Repository} at @acronym{CMU}.

@c The @uref{http://lib.stat.cmu.edu/S/faq, ``Frequently Asked Questions
@c about S''} contains further information about S, but is not
@c up-to-date.

@node What is S-PLUS?, What are the differences between R and S?, What is S?, R and S
@section What is @sc{S-Plus}?

@SPLUS{} is a value-added version of S sold by Insightful Corporation.
Based on the S language, @SPLUS{} provides functionality in a wide
variety of areas, including robust regression, modern non-parametric
regression, time series, survival analysis, multivariate analysis,
classical statistical tests, quality control, and graphics drivers.
Add-on modules add additional capabilities for wavelet analysis, spatial
statistics, GARCH models, and design of experiments.

See the @uref{http://www.insightful.com/products/splus/, Insightful
@SPLUS{} page} for further information.

@node What are the differences between R and S?, Is there anything R can do that S-PLUS cannot?, What is S-PLUS?, R and S
@section What are the differences between R and S?

We can regard S as a language with three current implementations or
``engines'', the ``old S engine'' (S version 3; @SPLUS{} 3.x and 4.x),
the ``new S engine'' (S version 4; @SPLUS{} 5.x and above), and R.
Given this understanding, asking for ``the differences between R and S''
really amounts to asking for the specifics of the R implementation of
the S language, i.e., the difference between the R and S engines.

For the remainder of this section, ``S'' refers to the S engines and not
the S language.

@menu
* Lexical scoping::             
* Models::                      
* Others::                      
@end menu

@node Lexical scoping, Models, What are the differences between R and S?, What are the differences between R and S?
@subsection Lexical scoping

Contrary to other implementations of the S language, R has adopted the
evaluation model of Scheme.

This difference becomes manifest when @emph{free} variables occur in a
function.  Free variables are those which are neither formal parameters
(occurring in the argument list of the function) nor local variables
(created by assigning to them in the body of the function).  Whereas S
(like C) by default uses @emph{static} scoping, R (like Scheme) has
adopted @emph{lexical} scoping.  This means the values of free variables
are determined by a set of global variables in S, but in R by the
bindings that were in effect at the time the function was created.

Consider the following function:

@smallexample
@group
cube <- function(n) @{
  sq <- function() n * n
  n * sq()
@}
@end group
@end smallexample

Under S, @code{sq()} does not ``know'' about the variable @code{n}
unless it is defined globally:

@smallexample
@group
S> cube(2)
Error in sq():  Object "n" not found
Dumped
S> n <- 3
S> cube(2)
[1] 18
@end group
@end smallexample

In R, the ``environment'' created when @code{cube()} was invoked is
also looked in:

@smallexample
@group
R> cube(2)
[1] 8
@end group
@end smallexample

@c The following more `realistic' example illustrating the differences in
@c scoping is due to @email{tlumley@@u.washington.edu, Thomas Lumley}.
@c The function

@c @smallexample
@c jackknife.lm <- function(lmobj) @{
@c   n <- length(resid(lmobj))
@c   jval <- sapply(1:n, function(i) coef(update(lmobj, subset = -i)))
@c   (n - 1) * (n - 1) * var(jval) / n
@c @}
@c @end smallexample

@c @noindent
@c does something useful in R, but does not work in S.  In order to make it
@c work in S you need to explicitly pass the linear model object into the
@c function nested in @code{apply()}.  If you don't and you are lucky you
@c will get @samp{Error: Object "lmobj" not found}.  If you are unlucky
@c enough to have a linear model called @code{lmobj} in your global
@c environment you will get the wrong answer with no warning.

@c The following version works in S.

@c @smallexample
@c jackknife.S.lm <- function(lmobj) @{
@c   n <- length(resid(lmobj))
@c   jval <- sapply(1:n,
@c                  function(i, lmobj) coef(update(lmobj, subset = -i)), 
@c                  lmobj = lmobj)
@c   (n - 1) * (n - 1) * var(jval) / n
@c @}
@c @end smallexample

@c (The S version was written independently by Thomas and at least three of
@c his fellow students over the past couple of years, causing literally
@c hours of confusion on each occasion.)

As a more ``interesting'' real-world problem, suppose you want to write
a function which returns the density function of the @math{r}-th order
statistic from a sample of size @math{n} from a (continuous)
distribution.  For simplicity, we shall use both the cdf and pdf of the
distribution as explicit arguments.  (Example compiled from various
postings by Luke Tierney.)

The @SPLUS{} documentation for @code{call()} basically suggests the
following:

@smallexample
@group
dorder <- function(n, r, pfun, dfun) @{
  f <- function(x) NULL
  con <- round(exp(lgamma(n + 1) - lgamma(r) - lgamma(n - r + 1)))
  PF <- call(substitute(pfun), as.name("x"))
  DF <- call(substitute(dfun), as.name("x"))
  f[[length(f)]] <-
    call("*", con,
         call("*", call("^", PF, r - 1),
              call("*", call("^", call("-", 1, PF), n - r),
                   DF)))
  f
@}
@end group
@end smallexample

@noindent Rather tricky, isn't it?  The code uses the fact that in S,
functions are just lists of special mode with the function body as the
last argument, and hence does not work in R (one could make the idea
work, though).

A version which makes heavy use of @code{substitute()} and seems to work
under both S and R is

@smallexample
@group
dorder <- function(n, r, pfun, dfun) @{
  con <- round(exp(lgamma(n + 1) - lgamma(r) - lgamma(n - r + 1)))
  eval(substitute(function(x) K * PF(x)^a * (1 - PF(x))^b * DF(x),
                  list(PF = substitute(pfun), DF = substitute(dfun),
                       a = r - 1, b = n - r, K = con)))
@}
@end group
@end smallexample

@noindent
(the @code{eval()} is not needed in S).

However, in R there is a much easier solution:

@smallexample
@group
dorder <- function(n, r, pfun, dfun) @{
  con <- round(exp(lgamma(n + 1) - lgamma(r) - lgamma(n - r + 1)))
  function(x) @{
    con * pfun(x)^(r - 1) * (1 - pfun(x))^(n - r) * dfun(x)
  @}
@}
@end group
@end smallexample

@noindent
This seems to be the ``natural'' implementation, and it works because
the free variables in the returned function can be looked up in the
defining environment (this is lexical scope).

Note that what you really need is the function @emph{closure}, i.e., the
body along with all variable bindings needed for evaluating it.  Since
in the above version, the free variables in the value function are not
modified, you can actually use it in S as well if you abstract out the
closure operation into a function @code{MC()} (for ``make closure''):

@smallexample
@group
dorder <- function(n, r, pfun, dfun) @{
  con <- round(exp(lgamma(n + 1) - lgamma(r) - lgamma(n - r + 1)))
  MC(function(x) @{
       con * pfun(x)^(r - 1) * (1 - pfun(x))^(n - r) * dfun(x)
     @},
     list(con = con, pfun = pfun, dfun = dfun, r = r, n = n))
@}
@end group
@end smallexample

Given the appropriate definitions of the closure operator, this works in
both R and S, and is much ``cleaner'' than a substitute/eval solution
(or one which overrules the default scoping rules by using explicit
access to evaluation frames, as is of course possible in both R and S).

For R, @code{MC()} simply is

@smallexample
MC <- function(f, env) f
@end smallexample

@noindent (lexical scope!), a version for S is

@smallexample
@group
MC <- function(f, env = NULL) @{
  env <- as.list(env)
  if (mode(f) != "function")
    stop(paste("not a function:", f))
  if (length(env) > 0 && any(names(env) == ""))
    stop(paste("not all arguments are named:", env))
  fargs <- if(length(f) > 1) f[1:(length(f) - 1)] else NULL
  fargs <- c(fargs, env)
  if (any(duplicated(names(fargs))))
    stop(paste("duplicated arguments:", paste(names(fargs)),
         collapse = ", "))
  fbody <- f[length(f)]
  cf <- c(fargs, fbody)
  mode(cf) <- "function"
  return(cf)
@}
@end group
@end smallexample

Similarly, most optimization (or zero-finding) routines need some
arguments to be optimized over and have other parameters that depend on
the data but are fixed with respect to optimization.  With R scoping
rules, this is a trivial problem; simply make up the function with the
required definitions in the same environment and scoping takes care of
it.  With S, one solution is to add an extra parameter to the function
and to the optimizer to pass in these extras, which however can only
work if the optimizer supports this.

Lexical scoping allows using function closures and maintaining local
state.  A simple example (taken from Abelson and Sussman) is obtained by
typing @kbd{demo(scoping)} at the R prompt.  Further information is
provided in the standard R reference ``R: A Language for Data Analysis
and Graphics'' (@pxref{What documentation exists for R?}) and in Robert
Gentleman and Ross Ihaka (2000), ``Lexical Scope and Statistical
Computing'', @uref{http://www.amstat.org/publications/jcgs/, ,
@emph{Journal of Computational and Graphical Statistics}}, @strong{9},
491--508.

Lexical scoping also implies a further major difference.  Whereas S
stores all objects as separate files in a directory somewhere (usually
@file{.Data} under the current directory), R does not.  All objects
in R are stored internally.  When R is started up it grabs a very large
piece of memory and uses it to store the objects.  R performs its own
memory management of this piece of memory.  Having everything in memory
is necessary because it is not really possible to externally maintain
all relevant ``environments'' of symbol/value pairs.  This difference
also seems to make R @emph{faster} than S.

The down side is that if R crashes you will lose all the work for the
current session.  Saving and restoring the memory ``images'' (the
functions and data stored in R's internal memory at any time) can be a
bit slow, especially if they are big.  In S this does not happen,
because everything is saved in disk files and if you crash nothing is
likely to happen to them.  (In fact, one might conjecture that the S
developers felt that the price of changing their approach to persistent
storage just to accommodate lexical scope was far too expensive.)
Hence, when doing important work, you might consider saving often (see
@ref{How can I save my workspace?}) to safeguard against possible
crashes.  Other possibilities are logging your sessions, or have your R
commands stored in text files which can be read in using
@code{source()}.

@quotation
@strong{Note:}  If you run R from within Emacs (see @ref{R and Emacs}),
you can save the contents of the interaction buffer to a file and
conveniently manipulate it using @code{ess-transcript-mode}, as well as
save source copies of all functions and data used.
@end quotation

@node Models, Others, Lexical scoping, What are the differences between R and S?
@subsection Models

There are some differences in the modeling code, such as

@itemize @bullet
@item
Whereas in S, you would use @code{lm(y ~ x^3)} to regress @code{y} on
@code{x^3}, in R, you have to insulate powers of numeric vectors (using
@code{I()}), i.e., you have to use @code{lm(y ~ I(x^3))}.
@item
The glm family objects are implemented differently in R and S.  The same
functionality is available but the components have different names.
@item
Option @code{na.action} is set to @code{"na.omit"} by default in R,
but not set in S.
@item
Terms objects are stored differently.  In S a terms object is an
expression with attributes, in R it is a formula with attributes.  The
attributes have the same names but are mostly stored differently.  The
major difference in functionality is that a terms object is
subscriptable in S but not in R.  If you can't imagine why this would
matter then you don't need to know.
@item
Finally, in R @code{y~x+0} is an alternative to @code{y~x-1} for
specifying a model with no intercept.  Models with no parameters at all
can be specified by @code{y~0}.
@end itemize

@node Others,  , Models, What are the differences between R and S?
@subsection  Others

Apart from lexical scoping and its implications, R follows the S
language definition in the Blue and White Books as much as possible, and
hence really is an ``implementation'' of S.  There are some intentional
differences where the behavior of S is considered ``not clean''.  In
general, the rationale is that R should help you detect programming
errors, while at the same time being as compatible as possible with S.

Some known differences are the following.

@itemize @bullet

@item
In R, if @code{x} is a list, then @code{x[i] <- NULL} and @code{x[[i]]
<- NULL} remove the specified elements from @code{x}.  The first of
these is incompatible with S, where it is a no-op.  (Note that you can
set elements to @code{NULL} using @code{x[i] <- list(NULL)}.)

@c @item
@c In R @code{x[-4]} fails if @code{x} is not @code{NULL} but has fewer
@c than 4 elements.  In S it has no effect.

@item
In S, the functions named @code{.First} and @code{.Last} in the
@file{.Data} directory can be used for customizing, as they are executed
at the very beginning and end of a session, respectively.

In R, the startup mechanism is as follows.  R first sources the system
startup file @file{@env{$@w{R_HOME}}/library/base/R/Rprofile}.  Then, it
searches for a site-wide startup profile unless the command line option
@option{--no-site-file} was given.  The name of this file is taken from
the value of the @env{R_PROFILE} environment variable.  If that variable
is unset, the default is @file{@env{$R_HOME}/etc/Rprofile}
@c <FIXME>
(@file{@env{$R_HOME}/etc/Rprofile.site} in R 1.4.0).
@ </FIXME>
This code is loaded in package @strong{base}.  Then, unless
@option{--no-init-file} was given, R searches for a file called
@file{.Rprofile} in the current directory or in the user's home
directory (in that order) and sources it into the user workspace.  It
then loads a saved image of the user workspace from @file{.RData}
 in case there is one (unless @option{--no-restore} was specified).  If
needed, the functions @code{.First()} and @code{.Last()} should be
defined in the appropriate startup profiles.

@item
In R, @code{T} and @code{F} are just variables being set to @code{TRUE}
and @code{FALSE}, respectively, but are not reserved words as in S and
hence can be overwritten by the user.  (This helps e.g.@: when you have
factors with levels @code{"T"} or @code{"F"}.)  Hence, when writing code
you should always use @code{TRUE} and @code{FALSE}.

@item
In R, @code{dyn.load()} can only load @emph{shared libraries}, as
created for example by @kbd{R CMD SHLIB}.

@item
In R, @code{attach()} currently only works for lists and data frames,
but not for directories.  (In fact, @code{attach()} also works for R
data files created with @code{save()}, which is analogous to attaching
directories in S.)  Also, you cannot attach at position 1.

@item
Categories do not exist in R, and never will as they are deprecated now
in S.  Use factors instead.

@item
In R, @code{For()} loops are not necessary and hence not supported.

@item
In R, @code{assign()} uses the argument @option{envir=} rather than
@option{where=} as in S.

@item
The random number generators are different, and the seeds have different
length.

@item
R passes integer objects to C as @code{int *} rather than @code{long *}
as in S.

@item
R has no single precision storage mode.  However, as of version 0.65.1,
there is a single precision interface to C/@FORTRAN{} subroutines.

@item
By default, @code{ls()} returns the names of the objects in the current
(under R) and global (under S) environment, respectively.  For example,
given

@smallexample
x <- 1; fun <- function() @{y <- 1; ls()@}
@end smallexample

@noindent
then @code{fun()} returns @code{"y"} in R and @code{"x"} (together with
the rest of the global environment) in S.

@item
R allows for zero-extent matrices (and arrays, i.e., some elements of
the @code{dim} attribute vector can be 0).  This has been determined a
useful feature as it helps reducing the need for special-case tests for
empty subsets.  For example, if @code{x} is a matrix, @code{x[, FALSE]}
is not @code{NULL} but a ``matrix'' with 0 columns.  Hence, such objects
need to be tested for by checking whether their @code{length()} is zero
(which works in both R and S), and not using @code{is.null()}.

@item
Named vectors are considered vectors in R but not in S (e.g.,
@code{is.vector(c(a = 1:3))} returns @code{FALSE} in S and @code{TRUE}
in R).

@item
Data frames are not considered as matrices in R (i.e., if @code{DF} is a
data frame, then @code{is.matrix(DF)} returns @code{FALSE} in R and
@code{TRUE} in S).

@item
R by default uses treatment contrasts in the unordered case, whereas S
uses the Helmert ones.  This is a deliberate difference reflecting the
opinion that treatment contrasts are more natural.

@item
In R, the last argument (which corresponds to the right hand side) of an
assignment function must be named @samp{value}.  E.g., @code{fun(a) <-
b} is evaluated as @code{(fun<-)(a, value = b)}.

@item
In S, @code{substitute()} searches for names for substitution in the
given expression in three places: the actual and the default arguments
of the matching call, and the local frame (in that order).  R looks in
the local frame only, with the special rule to use a ``promise'' if a
variable is not evaluated.  Since the local frame is initialized with
the actual arguments or the default expressions, this is usually
equivalent to S, until assignment takes place.

@item
In R, @code{eval(EXPR, sys.parent())} does not work.  Instead, one
should use either @code{eval(EXPR, sys.frame(sys.parent())),} which also
works in S, or @code{eval(EXPR, parent.frame())}, which is more
efficient but does not work in S.

@item
In S, the index variable in a @code{for()} loop is local to the inside
of the loop.  In R it is local to the environment where the @code{for()}
statement is executed.

@item
In S, @code{tapply(simplify=TRUE)} returns a vector where R returns a
one-dimensional array (which can have named dimnames).

@item
In S(-@sc{Plus}) the C locale is used, whereas in R the current
operating system locale is used for determining which characters are
alphanumeric and how they are sorted.  This affects the set of valid
names for R objects (for example accented chars may be allowed in R) and
ordering in sorts and comparisons (such as whether @code{"aA" < "Bb"} is
true or false).  From version 1.2.0 the locale can be (re-)set in R by
the @code{Sys.setlocale()} function.

@item
In S, @code{missing(@var{arg})} remains @code{TRUE} if @var{arg} is
subsequently modified; in R it doesn't.

@item
From R version 1.3.0, @code{data.frame} strips @code{I()} when creating
(column) names.

@end itemize

There are also differences which are not intentional, and result from
missing or incorrect code in R.  The developers would appreciate hearing
about any deficiencies you may find (in a written report fully
documenting the difference as you see it).  Of course, it would be
useful if you were to implement the change yourself and make sure it
works.

@node Is there anything R can do that S-PLUS cannot?, What is R-plus?, What are the differences between R and S?, R and S
@section Is there anything R can do that @sc{S-Plus} cannot?

Since almost anything you can do in R has source code that you could
port to @SPLUS{} with little effort there will never be much you can do
in R that you couldn't do in @SPLUS{} if you wanted to.  (Note that
using lexical scoping may simplify matters considerably, though.)

R offers several graphics features that @SPLUS{} does not, such as finer
handling of line types, more convenient color handling (via palettes),
gamma correction for color, and, most importantly, mathematical
annotation in plot texts, via input expressions reminiscent of @TeX{}
constructs.  See the help page for @code{plotmath}, which features an
impressive on-line example.  More details can be found in Paul Murrell
and Ross Ihaka (2000), ``An Approach to Providing Mathematical
Annotation in Plots'', @uref{http://www.amstat.org/publications/jcgs/, ,
@emph{Journal of Computational and Graphical Statistics}}, @strong{9},
582--599.

@node What is R-plus?,  , Is there anything R can do that S-PLUS cannot?, R and S
@section What is R-plus?

There is no such thing.

@node R Web Interfaces, R Add-On Packages, R and S, Top
@chapter R Web Interfaces

@strong{Rcgi} is a CGI WWW interface to R by
@email{mjr@@stats.mth.uea.ac.uk, Mark J. Ray}.  Recent versions have the
ability to use ``embedded code'': you can mix user input and code,
allowing the @HTML{} author to do anything from load in data sets to
enter most of the commands for users without writing CGI scripts.
Graphical output is possible in PostScript or GIF formats and the
executed code is presented to the user for revision.

Demo and download are available from
@uref{http://www.mth.uea.ac.uk/~h089/Rcgi/}.

@strong{Rweb} is developed and maintained by
@email{jeff@@math.montana.edu, Jeff Banfield}.  The
@uref{http://www.math.montana.edu/Rweb/, Rweb Home Page} provides access
to all three versions of Rweb---a simple text entry form that returns
output and graphs, a more sophisticated Javascript version that provides
a multiple window environment, and a set of point and click modules that
are useful for introductory statistics courses and require no knowledge
of the R language.  All of the Rweb versions can analyze Web accessible
datasets if a @acronym{URL} is provided.

The paper ``Rweb: Web-based Statistical Analysis'', providing a detailed
explanation of the different versions of Rweb and an overview of how
Rweb works, was published in the Journal of Statistical Software
(@uref{http://www.stat.ucla.edu/journals/jss/v04/i01/}).

@node R Add-On Packages, R and Emacs, R Web Interfaces, Top
@chapter R Add-On Packages

@menu
* Which add-on packages exist for R?::  
* How can add-on packages be installed?::  
* How can add-on packages be used?::  
* How can add-on packages be removed?::  
* How can I create an R package?::  
* How can I contribute to R?::  
@end menu

@node Which add-on packages exist for R?, How can add-on packages be installed?, R Add-On Packages, R Add-On Packages
@section Which add-on packages exist for R?

The R distribution comes with the following extra packages:

@table @strong
@item ctest
A collection of Classical TESTs, including the Ansari-Bradley, Bartlett,
chi-squared, Fisher, Kruskal-Wallis, Kolmogorov-Smirnov, @math{t}, and
Wilcoxon tests.
@item eda
Exploratory Data Analysis.  Currently only contains functions for robust
line fitting, and median polish and smoothing.
@item lqs
Resistant regression and covariance estimation.
@item methods
Formally defined methods and classes for R objects, plus other
programming tools, as described in the Green Book.
@item modreg
MODern REGression: smoothing and local methods.
@item mva
MultiVariate Analysis.  Currently contains code for principal
components, canonical correlations, metric multidimensional scaling,
factor analysis, and hierarchical and @math{k}-means clustering.
@item nls
Nonlinear regression routines.
@item splines
Regression spline functions and classes.
@item stepfun
Code for dealing with STEP FUNctions, including empirical cumulative
distribution functions.
@item tcltk
Interface and language bindings to Tcl/Tk @acronym{GUI} elements.
@item ts
Time Series.
@end table

The following packages are available from the @acronym{CRAN}
@file{src/contrib} area.

@table @strong
@item AnalyzeFMRI
Functions for I/O, visualisation and analysis of functional Magnetic
Resonance Imaging (fMRI) datasets stored in the ANALYZE format.
@item CoCoAn
Constrained Correspondence Analysis.
@item Devore5
Data sets and sample analyses from ``Probability and Statistics for
Engineering and the Sciences (5th ed)'' by Jay L. Devore, 2000, Duxbury.
@item GLMMGibbs
Generalised Linear Mixed Models by Gibbs sampling.
@item GeneSOM
Clustering genes using Self-Organizing Maps (SOMs).
@item KernSmooth
Functions for kernel smoothing (and density estimation) corresponding to
the book ``Kernel Smoothing'' by M. P. Wand and M. C. Jones, 1995.
@item MASS
Functions and datasets from the main package of Venables and Ripley,
``Modern Applied Statistics with @SPLUS{}''.  Contained in the @file{VR}
bundle.
@item Matrix
A Matrix package.
@item NISTnls
A set of test nonlinear least squares examples from @acronym{NIST}, the
U.S. National Institute for Standards and Technology.
@item Oarray
Arrays with arbitrary offsets.
@item PHYLOGR
Manipulation and analysis of phylogenetically simulated data sets (as
obtained from PDSIMUL in package PDAP) and phylogenetically-based
analyses using GLS.
@item PTAk
A multiway method to decompose a tensor (array) of any order, as a
generalisation of SVD also supporting non-identity metrics and
penalisations.  Also includes some other multiway methods.
@item RArcInfo
Functions to import Arc/Info V7.x coverages and data.
@item RandomFields
Creating random fields using various methods.
@item RMySQL
An interface between R and the MySQL database system.
@item RODBC
An @acronym{ODBC} database interface.
@item RPgSQL
Provides methods for accessing data stored in PostgreSQL tables.
@item RmSQL
An interface between R and the mSQL database system.
@c @item Rnotes
@c The data sets for the exercises in ``An Introduction to R''
@c (@pxref{What documentation exists for R?}).
@item Rstreams
Binary file stream support functions.
@item Rwave
An environment for the time-frequency analysis of 1-D signals (and
especially for the wavelet and Gabor transforms of noisy signals), based
on the book ``Practical Time-Frequency Analysis: Gabor and Wavelet
Transforms with an Implementation in S'' by Rene Carmona, Wen L. Hwang
and Bruno Torresani, 1998, Academic Press.
@item SASmixed
Data sets and sample linear mixed effects analyses corresponding to the
examples in ``SAS System for Mixed Models'' by R. C. Littell,
G. A. Milliken, W. W. Stroup and R. D. Wolfinger, 1996, SAS Institute.
@item SuppDists
Ten distributions supplementing those built into R (Inverse Gauss,
Kruskal-Wallis, Kendall's Tau, Friedman's chi squared, Spearman's rho,
maximum F ratio, the Pearson product moment correlation coefficiant,
Johnson distributions, normal scores and generalized hypergeometric
distributions).
@item XML
Facilities for reading @acronym{XML} documents and DTDs.
@item acepack
ACE (Alternating Conditional Expectations) and AVAS (Additivity and
VAriance Stabilization for regression) methods for selecting regression
transformations.
@item adapt
Adaptive quadrature in up to 20 dimensions.
@item akima
Linear or cubic spline interpolation for irregularly gridded data.
@item ash
David Scott's ASH routines for 1D and 2D density estimation.
@item bindata
Generation of correlated artificial binary data.
@item blighty
Function for drawing the coastline of the United Kingdom.
@item boot
Functions and datasets for bootstrapping from the book ``Bootstrap
Methods and Their Applications'' by A. C. Davison and D. V. Hinkley,
1997, Cambridge University Press.
@item bootstrap
Software (bootstrap, cross-validation, jackknife), data and errata for
the book ``An Introduction to the Bootstrap'' by B. Efron and
R. Tibshirani, 1993, Chapman and Hall.
@item bqtl
QTL mapping toolkit for inbred crosses and recombinant inbred lines.
Includes maximum likelihood and Bayesian tools.
@item car
Companion to Applied Regression, containing functions for applied
regession, linear models, and generalized linear models, with an
emphasis on regression diagnostics, particularly graphical diagnostic
methods.
@item cclust
Convex clustering methods, including @math{k}-means algorithm, on-line
update algorithm (Hard Competitive Learning) and Neural Gas algorithm
(Soft Competitive Learning) and calculation of several indexes for
finding the number of clusters in a data set.
@item cfa
Analysis of configuration frequencies.
@item chron
A package for working with chronological objects (times and dates).
@item class
Functions for classification (@math{k}-nearest neighbor and LVQ).
Contained in the @file{VR} bundle.
@item cluster
Functions for cluster analysis.
@item cmprsk
Estimation, testing and regression modeling of subdistribution functions
in competing risks.
@item coda
Output analysis and diagnostics for Markov Chain Monte Carlo (MCMC)
simulations.
@item conf.design
A series of simple tools for constructing and manipulating confounded
and fractional factorial designs.
@item cramer
Routine for the multivariate nonparametric Cramer test.
@item date
Functions for dealing with dates.  The most useful of them accepts a
vector of input dates in any of the forms @samp{8/30/53},
@samp{30Aug53}, @samp{30 August 1953}, @dots{}, @samp{August 30 53}, or
any mixture of these.
@item diamonds
Functions for illustrating aperture-4 diamond partitions in the plane,
or on the surface of an octahedron or icosahedron, for use as analysis
or sampling grids.
@item dse
Dynamic System Estimation, a multivariate time series package.  Contains
@strong{dse1} (DSE kernel plus ARMA and state space models),
@strong{dse2} (DSE extensions), @strong{syskern} (functions for writing
code that is operating system and R/S independent), and @strong{tframe}
(functions for writing code that is independent of the representation of
time).
@item e1071
Miscellaneous functions used at the Department of Statistics at TU Wien
(E1071), including moments, short-time Fourier transforms, Independent
Component Analysis, Latent Class Analysis, reading and writing of images
in portable anymap format, simulation of a Wiener process, support
vector machines, and fuzzy clustering.
@item ellipse
Package for drawing ellipses and ellipse-like confidence regions.
@item event.chart
Package for creating event charts.
@item exactRankTests
Computes exact @math{p}-values and quantiles using an implementation of
the Streitberg/Roehmel shift algorithm.
@item fastICA
Implementation of FastICA algorithm to perform Independent Component
Analysis (ICA) and Projection Pursuit.
@item fdim
Functions for calculating fractal dimension.
@item fields
A collection of programs for curve and function fitting with an emphasis
on spatial data.  The major methods implemented include cubic and thin
plate splines, universal Kriging and Kriging for large data sets.  The
main feature is that any covariance function implemented in R can be
used for spatial prediction.
@item foreign
Functions for reading and writing data stored by statistical software
like Minitab, SAS, SPSS, Stata, etc.
@item fracdiff
Maximum likelihood estimation of the parameters of a fractionally
differenced ARIMA(@math{p,d,q}) model (Haslett and Raftery, Applied
Statistics, 1989).
@item gafit
Genetic algorithm for curve fitting.
@item gee
An implementation of the Liang/Zeger generalized estimating equation
approach to GLMs for dependent data.
@item geoR
Functions to perform geostatistical data analysis including model-based
methods.
@item gld
Basic functions for the generalised (Tukey) lambda distribution.
@item gregmisc
Miscellaneous functions written/maintained by Gregory R. Warnes.
@item gss
A comprehensive package for structural multivariate function estimation
using smoothing splines.
@item ineq
Inequality, concentration and poverty measures, and Lorenz curves
(empirical and theoretic).
@c  @item integrate
@c  Adaptive quadrature in up to 20 dimensions.
@item leaps
A package which performs an exhaustive search for the best subsets of a
given set of potential regressors, using a branch-and-bound algorithm,
and also performs searches using a number of less time-consuming
techniques.
@item lgtdl
A set of methods for longitudinal data objects.
@item lmtest
A collection of tests on the assumptions of linear regression models
from the book ``The linear regression model under test'' by W. Kraemer
and H. Sonnberger, 1986, Physica.
@item locfit
Local Regression, likelihood and density estimation.
@item logspline
Logspline density estimation.
@item lokern
Kernel regression smoothing with adaptive local or global plug-in
bandwidth selection.
@item lpridge
Local polynomial (ridge) regression.
@item maptree
Functions with example data for graphing and mapping models from
hierarchical clustering and classification and regression trees.
@item maxstat
Maximally selected rank and Gauss statistics with several p-value
approximations.
@item mclust
Model-based cluster analysis.
@item mda
Code for mixture discriminant analysis (MDA), flexible discriminant
analysis (FDA), penalized discriminant analysis (PDA), multivariate
additive regression splines (MARS), adaptive back-fitting splines
(BRUTO), and penalized regression.
@item meanscore
Mean Score method for missing covariate data in logistic regression
models.
@item mgcv
Routines for GAMs and other genralized ridge regression problems with
multiple smoothing parameter selection by GCV or UBRE.
@item mlbench
A collection of artificial and real-world machine learning benchmark
problems, including the Boston housing data.
@item muhaz
Hazard function estimation in survival analysis.
@item multiv
Functions for hierarchical clustering, partitioning, bond energy
algorithm, Sammon mapping, PCA and correspondence analysis.
@item mvnmle
ML estimation for multivariate normal data with missing values.
@item mvtnorm
Multivariate normal and @math{t} distributions.
@item netCDF
Read data from netCDF files.
@item nlme
Fit and compare Gaussian linear and nonlinear mixed-effects models.
@item nlrq
Nonlinear quantile regression.
@item nnet
Software for single hidden layer perceptrons (``feed-forward neural
networks''), and for multinomial log-linear models.  Contained in the
@file{VR} bundle.
@item norm
Analysis of multivariate normal datasets with missing values.
@item odesolve
An interface for the Ordinary Differential Equation (ODE) solver lsoda.
ODEs are expressed as R functions.
@item oz
Functions for plotting Australia's coastline and state boundaries.
@item panel
Functions and datasets for fitting models to Panel data.
@item pcurve
Fits a principal curve to a numeric multivariate dataset in arbitrary
dimensions.  Produces diagnostic plots.  Also calculates Bray-Curtis and
other distance matrices and performs multi-dimensional scaling and
principal component analyses.
@item permax
Functions intended to facilitate certain basic analyses of DNA array
data, especially with regard to comparing expression levels between two
types of tissue.
@item pinktoe
Converts S trees to @HTML{}/Perl files for interactive tree traversal.
@item polymars
Polychotomous regression based on Multivariate Adaptive Regression
Splines.
@item polynom
A collection of functions to implement a class for univariate polynomial
manipulations.
@item princurve
Fits a principal curve to a matrix of points in arbitrary dimension.
@item pspline
Smoothing splines with penalties on order @math{m} derivatives.
@item quadprog
For solving quadratic programming problems.
@item quantreg
Quantile  regression and related methods.
@c @item ratetables
@c US national and state mortality data (requires @strong{survival4} and
@c @strong{date}), for use with @strong{survival4}.
@item rmeta
Functions for simple fixed and random effects meta-analysis for
two-sample comparison of binary outcomes.
@item rpart
Recursive PARTitioning and regression trees.
@item scatterplot3d
Plots a three dimensional (3D) point cloud perspectively.
@item sem
Functions for fitting general linear Structural Equation Models (with
observed and unobserved variables) by the method of maximum likelihood
using the RAM approach.
@item sgeostat
An object-oriented framework for geostatistical modeling.
@item sm
Software linked to the book ``Applied Smoothing Techniques for Data
Analysis:  The Kernel Approach with @SPLUS{} Illustrations'' by
A. W. Bowman and A. Azzalini (1997), Oxford University Press.
@item sma
Functions for exploratory (statistical) microarray analysis.
@item sn
Functions for manipulating skew-normal probability distributions and for
fitting them to data, in the scalar and the multivariate case.
@item sna
A range of tools for social network analysis, including node and
graph-level indices, structural distance and covariance methods,
structural equivalence detection, p* modeling, and network
visualization.
@c @item snns
@c An R interface to the Stuttgart Neural Networks Simulator (SNNS).
@item spatial
Functions for kriging and point pattern analysis from ``Modern Applied
Statistics with @SPLUS{}'' by W. Venables and B. Ripley.  Contained in
the @file{VR} bundle.
@item splancs
Spatial and space-time point pattern analysis functions.
@c @item stable
@c Density, distribution, quantile and hazard functions of a stable
@c variate; generalized linear models for the parameters of a stable
@c distribution.
@c @item stataread
@c Read and write Stata v5 and v6 @file{.dta} files.
@item strucchange
Various tests on structural change in linear regression models.
@c @item survival4
@c Functions for survival analysis, version 4 (requires
@c @strong{splines}).
@item survival
Functions for survival analysis, including penalised likelihood.
@item tensor
Tensor product of arrays.
@item tree
Classification and regression trees.
@item tripack
A constrained two-dimensional Delaunay triangulation package.
@item tseries
Package for time series analysis with emphasis on non-linear modelling.
@item twostage
Functions for optimal design of two-stage-studies using the Mean Score
method.
@item wavethresh
Software to perform 1-d and 2-d wavelet statistics and transforms.
@item wle
Robust statistical inference via a weighted likelihood approach.
@item xgobi
Interface to the XGobi and XGvis programs for graphical data analysis.
@item xtable
Export data to La@TeX{} and @HTML{} tables.
@item zmatrix
Matrices with numeric indices starting at zero rather than one.
@end table

@noindent
See @acronym{CRAN} @file{src/contrib/PACKAGES} for more information.

There is also a @acronym{CRAN} @file{src/contrib/Devel} directory which
contains packages still ``under development'' or depending on features
only present in the current development versions of R.  Volunteers are
invited to give these a try, of course.  This area of @acronym{CRAN}
currently contains

@table @strong
@item GRASS
Interface between the GRASS geographical information system and R, based
on starting R from within the GRASS environment and chosen LOCATION and
MAPSET.  Wrapper and helper functions are provided for a range of R
functions to match the interface metadata structures.
@item GenKern
Functions for generating and manipulating generalised binned kernel
density estimates.
@item R2HTML
Functions for exporting R objects & graphics in an @HTML{} document.
@item StatDataML
Read and write StatDataML.
@item cxx
A small C++ test package.
@item dopt
Finding D-optimal experimental designs.
@item dseplus
Extensions to @strong{dse}, the Dynamic Systems Estimation multivariate
time series package.  Contains PADI, juice and monitoring extensions.
@item ensemble
Ensembles of tree classifiers.
@item grid
The Grid graphics package, a rewrite of the graphics layout
capabilities, plus some support for interaction.
@item hdf5
Interface to the @acronym{NCSA} HDF5 library.
@item hpower
A suite of functions to compute power and sample size for tests of the
general linear hypothesis.
@item lattice
Lattice graphics, an implementation of Trellis Graphics functions.
@item multidim
Code for correspondence analysis and other multidimensional descriptive
statistics.
@item multilm
A basic method for fitting and testing multivariate linear models,
including stabilized test procedures by Laeuter et.@: al.
@item npConfRatio
Nonparametric confidence intervals for the ratios of medians.
@item pls
Univariate Partial Least Squares Regression.
@item regexp
Simple regular expression interface.
@item write.snns
Function for writing a @acronym{SNNS} pattern file from a data frame or
matrix.
@end table

Directory @file{src/contrib/Omegahat} contains yet unreleased packages
from the @uref{http://www.omegahat.org/, Omegahat Project for
Statistical Computing}.  Currently, there are

@table @strong
@item CORBA
Dynamic CORBA client/server facilities for R.  Connects to other
CORBA-aware applications developed in arbitrary languages, on different
machines and allows R functionality to be exported in the same way to
other applications.
@item OOP
OOP style classes and methods for R and @SPLUS{}.  Object references and
class-based method definition are supported in the style of languages
such as Java and C++.
@item REmbeddedPostgres
Allows R functions and objects to be used to implement SQL functions ---
per-record, aggregate and trigger functions.
@item RGnumeric
A plugin for the Gnumeric spreadsheet that allows R functions to be
called from cells within the sheet, automatic recalculation, etc.
@item RJavaDevice
A graphics device for R that uses Java components and graphics
@acronym{API}s.
@item RSMethods
An implementation of S version 4 methods and classes for R, consistent
with the basic material in ``Programming with data'' by John
M. Chambers, 1998, Springer NY.
@item RSPerl
An interface from R to an embedded, persistent Perl interpreter,
allowing one to call arbitrary Perl subroutines, classes and methods.
@item RSPython
Allows Python programs to invoke S functions, methods, etc., and S code
to call Python functionality.
@item SASXML
Example for reading XML files in SAS 8.2 manner.
@item SJava
An interface from R to Java to create and call Java objects and
methods.
@item SLanguage
Functions and C support utilities to support S language programming
that can work in both R and @SPLUS{}.
@item SNetscape
Plugin for Netscape and JavaScript.
@item SXalan
Process XML documents using XSL functions implemented in R and
dynamically substituting output from R.
@item Slcc
Parses C source code, allowing one to analyze and automatically generate
interfaces from S to that code, including the table of S-accessible
native symbols, parameter count and type information, S constructors
from C objects, call graphs, etc.
@item Sxslt
An extension module for libxslt, the XML-XSL document translator, that
allows XSL functions to be implemented via R functions.
@end table

@email{jlindsey@@luc.ac.be, Jim Lindsey} has written a collection of R
packages for nonlinear regression and repeated measurements, consisting
of @strong{event} (event history procedures and models), @strong{gnlm}
(generalized nonlinear regression models), @strong{growth} (multivariate
normal and elliptically-contoured repeated measurements models),
@strong{repeated} (non-normal repeated measurements models),
@strong{rmutil} (utilities for nonlinear regression and repeated
measurements), and @strong{stable} (probability functions and
generalized regression models for stable distributions).  All analyses
in the new edition of his book ``Models for Repeated Measurements''
(1999, Oxford University Press) were carried out using these packages.
Jim has also started @strong{dna}, a package with procedures for the
analysis of DNA sequences.  Jim's packages can be obtained from
@uref{http://www.luc.ac.be/~jlindsey/rcode.html}.

@c @email{hfe@@math.uio.no, Harald Fekjaer} has written @strong{addreg}, a
@c package for additive hazards regression, which can be obtained from
@c @uref{http://www.med.uio.no/imb/stat/addreg/}.

More code has been posted to the r-help mailing list, and can be
obtained from the mailing list archive.

@node How can add-on packages be installed?, How can add-on packages be used?, Which add-on packages exist for R?, R Add-On Packages
@section How can add-on packages be installed?

(Unix only.)  The add-on packages on @acronym{CRAN} come as gzipped tar
files named @code{@var{pkg}_@var{version}.tar.gz}, which may in fact be
``bundles'' containing more than one package.  Provided that
@command{tar} and @command{gzip} are available on your system, type

@smallexample
$ R CMD INSTALL /path/to/@var{pkg}_@var{version}.tar.gz
@end smallexample

@noindent
at the shell prompt to install to the library tree rooted at the first
directory given in @env{R_LIBS} (see below) if this is set and non-null,
and to the default library (the @file{library} subdirectory of
@file{R_HOME}) otherwise.  (Versions of R prior to 1.3.0 installed to
the default library by default.)

To install to another tree (e.g., your private one), use

@smallexample
$ R CMD INSTALL -l @var{lib} /path/to/@var{pkg}_@var{version}.tar.gz
@end smallexample

@noindent
where @var{lib} gives the path to the library tree to install to.

Even more conveniently, you can install and automatically update
packages from within R if you have access to @acronym{CRAN}.  See the
help page for @code{CRAN.packages()} for more information.

You can use several library trees of add-on packages.  The easiest way
to tell R to use these is via the environment variable @env{R_LIBS}
which should be a colon-separated list of directories at which R library
trees are rooted.  You do not have to specify the default tree in
@env{R_LIBS}.  E.g., to use a private tree in @file{$HOME/lib/R} and a
public site-wide tree in @file{/usr/local/lib/R-contrib}, put

@smallexample
R_LIBS="$HOME/lib/R:/usr/local/lib/R-contrib"; export R_LIBS
@end smallexample

@noindent
into your (Bourne) shell profile or even preferably, add the line

@smallexample
R_LIBS="$HOME/lib/R:/usr/local/lib/R-contrib"
@end smallexample

@noindent
your @file{~/.Renviron} file.  (Note that no @code{export} statement is
needed or allowed in this file; see the on-line help for @code{Startup}
for more information.)

@node How can add-on packages be used?, How can add-on packages be removed?, How can add-on packages be installed?, R Add-On Packages
@section How can add-on packages be used?

To find out which additional packages are available on your system, type

@smallexample
library()
@end smallexample

@noindent
at the R prompt.  

This produces something like

@smallexample
Packages in `/home/me/lib/R':

mystuff       My own R functions, nicely packaged but not documented

Packages in `/usr/local/lib/R/library':

KernSmooth    Functions for kernel smoothing for Wand & Jones (1995)
MASS          Main Library of Venables and Ripley's MASS
base          The R base package
boot          Bootstrap R (S-Plus) Functions (Canty)
class         Functions for classification
cluster       Functions for clustering (by Rousseeuw et al.)
ctest         Classical Tests
eda           Exploratory Data Analysis
foreign       Read data stored by Minitab, S, SAS, SPSS, Stata, ...
lqs           Resistant Regression and Covariance Estimation
mgcv          Multiple smoothing parameter estimation and GAMs by GCV
modreg        Modern Regression: Smoothing and Local Methods
mva           Classical Multivariate Analysis
nlme          Linear and nonlinear mixed effects models
nls           Nonlinear regression
nnet          Feed-forward neural networks and multinomial log-linear
              models
rpart         Recursive partitioning
spatial       functions for kriging and point pattern analysis
splines       Regression Spline Functions and Classes
stepfun       Step Functions, including Empirical Distributions
survival      Survival analysis, including penalised likelihood
tcltk         Interface to Tcl/Tk
ts            Time series functions
@end smallexample

You can ``load'' the installed package @var{pkg} by

@smallexample
library(@var{pkg})
@end smallexample

You can then find out which functions it provides by typing one of

@smallexample
library(help = @var{pkg})
help(package = @var{pkg})
@end smallexample

You can unload the loaded package @var{pkg} by

@smallexample
detach("package:@var{pkg}")
@end smallexample

@node How can add-on packages be removed?, How can I create an R package?, How can add-on packages be used?, R Add-On Packages
@section How can add-on packages be removed?

Use

@smallexample
$ R CMD REMOVE @var{pkg_1} @dots{} @var{pkg_n}
@end smallexample

@noindent
to remove the packages @var{pkg_1}, @dots{}, @var{pkg_n} from the
library tree rooted at the first directory given in @env{R_LIBS} if this
is set and non-null, and from the default library otherwise.  (Versions
of R prior to 1.3.0 removed from the default library by default.)

To remove from library @var{lib}, do

@smallexample
$ R CMD REMOVE -l @var{lib} @var{pkg_1} @dots{} @var{pkg_n}
@end smallexample

@node How can I create an R package?, How can I contribute to R?, How can add-on packages be removed?, R Add-On Packages
@section How can I create an R package?

A package consists of a subdirectory containing the files
@file{DESCRIPTION} and @file{INDEX}, and the subdirectories @file{R},
@file{data}, @file{demo}, @file{exec}, @file{inst}, @file{man},
@file{src}, and @file{tests} (some of which can be missing).  Optionally
the package can also contain script files @file{configure} and
@file{cleanup} which are executed before and after installation.

@ifclear UseExternalXrefs
See section ``Creating R packages'' in @cite{Writing R Extensions}, for
details.
@end ifclear
@ifset UseExternalXrefs
@xref{Creating R packages, , Creating R packages, R-exts, Writing R
Extensions}, for details.
@end ifset
This manual is included in the R distribution, @pxref{What documentation
exists for R?}, and gives information on package structure, the
configure and cleanup mechanisms, and on automated package checking and
building.

R version 1.3.0 has added the function @code{package.skeleton()} which
will set up directories, save data and code, and create skeleton help
files for a set of R functions and datasets.


@xref{What is CRAN?}, for information on uploading a package to CRAN.

@node How can I contribute to R?,  , How can I create an R package?, R Add-On Packages
@section How can I contribute to R?

R is in active development and there is always a risk of bugs creeping
in.  Also, the developers do not have access to all possible machines
capable of running R.  So, simply using it and communicating problems is
certainly of great value.

One place where functionality is still missing is the modeling software
as described in ``Statistical Models in S'' (see @ref{What is S?});
Generalized Additive Models (@pxref{Are GAMs implemented in R?}) and
some of the nonlinear modeling code are not there yet.

The @uref{http://developer.r-project.org/, R Developer Page} acts as an
intermediate repository for more or less finalized ideas and plans for
the R statistical system.  It contains (pointers to) TODO lists, RFCs,
various other writeups, ideas lists, and CVS miscellanea.

Many (more) of the packages available at the Statlib S Repository might
be worth porting to R.

If you are interested in working on any of these projects, please notify
@email{Kurt.Hornik@@r-project.org, Kurt Hornik}.

@node R and Emacs, R Miscellanea, R Add-On Packages, Top
@chapter R and Emacs

@menu
* Is there Emacs support for R?::  
* Should I run R from within Emacs?::  
* Debugging R from within Emacs::  
@end menu

@node Is there Emacs support for R?, Should I run R from within Emacs?, R and Emacs, R and Emacs
@section Is there Emacs support for R?

There is an Emacs package called @acronym{ESS} (``Emacs Speaks
Statistics'') which provides a standard interface between statistical
programs and statistical processes.  It is intended to provide
assistance for interactive statistical programming and data analysis.
Languages supported include: S dialects (S 3/4, @SPLUS{} 3.x/4.x/5.x,
and R), LispStat dialects (XLispStat, ViSta), SAS, Stata, SPSS dialects
(SPSS, Fiasco) and SCA.

@acronym{ESS} grew out of the need for bug fixes and extensions to
S-mode 4.8 (which was a @acronym{GNU} Emacs interface to S/@SPLUS{}
version 3 only).  The current set of developers desired support for
XEmacs, R, S4, and MS Windows.  In addition, with new modes being
developed for R, Stata, and SAS, it was felt that a unifying interface
and framework for the user interface would benefit both the user and the
developer, by helping both groups conform to standard Emacs usage.  The
end result is an increase in efficiency for statistical programming and
data analysis, over the usual tools.

R support contains code for editing R source code (syntactic indentation
and highlighting of source code, partial evaluations of code, loading
and error-checking of code, and source code revision maintenance) and
documentation (syntactic indentation and highlighting of source code,
sending examples to running @acronym{ESS} process, and previewing),
interacting with an inferior R process from within Emacs (command-line
editing, searchable command history, command-line completion of R object
and file names, quick access to object and search lists, transcript
recording, and an interface to the help system), and transcript
manipulation (recording and saving transcript files, manipulating and
editing saved transcripts, and re-evaluating commands from transcript
files).

The latest versions of @acronym{ESS} are available from
@uref{http://ess.stat.wisc.edu/pub/ESS/} or
@uref{ftp://ess.stat.wisc.edu/pub/ESS/}, or via @acronym{CRAN}.  The
@HTML{} version of the documentation can be found at
@uref{http://stat.ethz.ch/ESS/}.

@acronym{ESS} comes with detailed installation instructions.

For help with @acronym{ESS}, send email to
@email{ESS-help@@stat.ethz.ch}.

Please send bug reports and suggestions on @acronym{ESS} to
@email{ESS-bugs@@stat.math.ethz.ch}.  The easiest way to do this from is
within Emacs by typing @kbd{M-x ess-submit-bug-report} or using the
[ESS] or [iESS] pulldown menus.

@node Should I run R from within Emacs?, Debugging R from within Emacs, Is there Emacs support for R?, R and Emacs
@section Should I run R from within Emacs?

Yes, @emph{definitely}.  Inferior R mode provides a readline/history
mechanism, object name completion, and syntax-based highlighting of the
interaction buffer using Font Lock mode, as well as a very convenient
interface to the R help system.

Of course, it also integrates nicely with the mechanisms for editing R
source using Emacs.  One can write code in one Emacs buffer and send
whole or parts of it for execution to R; this is helpful for both data
analysis and programming.  One can also seamlessly integrate with a
revision control system, in order to maintain a log of changes in your
programs and data, as well as to allow for the retrieval of past
versions of the code.

In addition, it allows you to keep a record of your session, which can
also be used for error recovery through the use of the transcript mode.

To specify command line arguments for the inferior R process, use
@kbd{C-u M-x R} for starting R.

@c This prompts you for the arguments; in particular, you can increase
@c the memory size this way (@pxref{Why does R run out of memory?}).

@node Debugging R from within Emacs,  , Should I run R from within Emacs?, R and Emacs
@section Debugging R from within Emacs

To debug R ``from within Emacs'', there are several possibilities.  To
use the Emacs GUD (Grand Unified Debugger) library with the recommended
debugger GDB, type @kbd{M-x gdb} and give the path to the R
@emph{binary} as argument.  At the gdb prompt, set @env{R_HOME} and
other environment variables as needed (using e.g.@: @kbd{set env R_HOME
/path/to/R/}, but see also below), and start the binary with the desired
arguments (e.g., @kbd{run --vsize=12M}).

If you have @acronym{ESS}, you can do @kbd{C-u M-x R @key{RET} - d
@key{SPC} g d b @key{RET}} to start an inferior R process with arguments
@option{-d gdb}.

A third option is to start an inferior R process via @acronym{ESS}
(@kbd{M-x R}) and then start GUD (@kbd{M-x gdb}) giving the R binary
(using its full path name) as the program to debug.  Use the program
@command{ps} to find the process number of the currently running R
process then use the @code{attach} command in gdb to attach it to that
process.  One advantage of this method is that you have separate
@code{*R*} and @code{*gud-gdb*} windows.  Within the @code{*R*} window
you have all the @acronym{ESS} facilities, such as object-name
completion, that we know and love.

When using GUD mode for debugging from within Emacs, you may find it
most convenient to use the directory with your code in it as the current
working directory and then make a symbolic link from that directory to
the R binary.  That way @file{.gdbinit} can stay in the directory with
the code and be used to set up the environment and the search paths for
the source, e.g.@: as follows:

@smallexample
set env R_HOME /opt/R
set env R_PAPERSIZE letter
set env R_PRINTCMD lpr
dir /opt/R/src/appl
dir /opt/R/src/main
dir /opt/R/src/nmath
dir /opt/R/src/unix
@end smallexample

@node R Miscellanea, R Programming, R and Emacs, Top
@chapter R Miscellanea

@menu
* Why does R run out of memory?::  
* Why does sourcing a correct file fail?::  
* How can I set components of a list to NULL?::  
* How can I save my workspace?::  
* How can I clean up my workspace?::  
* How can I get eval() and D() to work?::  
* Why do my matrices lose dimensions?::  
* How does autoloading work?::  
* How should I set options?::   
* How do file names work in Windows?::  
* Why does plotting give a color allocation error?::  
* How do I convert factors to numeric?::  
* Are Trellis displays implemented in R?::  
* What are the enclosing and parent environments?::  
* How can I substitute into a plot label?::  
* What are valid names?::       
* Are GAMs implemented in R?::  
* Why is the output not printed when I source() a file?::  
* Why does outer() behave strangely with my function?::  
@end menu

@node Why does R run out of memory?, Why does sourcing a correct file fail?, R Miscellanea, R Miscellanea
@section Why does R run out of memory?

@c  R (currently) uses a @emph{static} memory model.  This means that when
@c  it starts up, it asks the operating system to reserve a fixed amount of
@c  memory for it.  The size of this chunk cannot be changed subsequently.
@c  Hence, it can happen that not enough memory was allocated, e.g., when
@c  trying to read large data sets into R.

@c  In these cases, you should restart R with more memory available, using
@c  the command line options @option{--nsize} and @option{--vsize}.  To
@c  understand these options, one needs to know that R maintains separate
@c  areas for fixed and variable sized objects.  The first of these is
@c  allocated as an array of ``cons cells'' (Lisp programmers will know what
@c  they are, others may think of them as the building blocks of the
@c  language itself, parse trees, etc.), and the second are thrown on a
@c  ``heap''.  The @option{--nsize} option can be used to specify the number
@c  of cons cells which R is to use (the default is 250000), and the
@c  @option{--vsize} option to specify the size of the vector heap in bytes
@c  (the default is @w{6 MB}).  Both options must either be integers or
@c  integers ending with @samp{M}, @samp{K}, or @samp{k} meaning `Mega'
@c  (2^20), (computer) `Kilo' (2^10), or regular `kilo' (1000).

@c  E.g., to read in a table of 5000 observations on 40 numeric variables,
@c  @samp{R --vsize=6M} should do (which currently is the default).

@c  Note that the information on where to find vectors and strings on the
@c  heap is stored using cons cells.  Thus, it may also be necessary to
@c  allocate more space for cons cells in order to perform computations with
@c  very ``large'' variable-size objects.

@c  You can find out the current memory consumption (the proportion of heap
@c  and cons cells used) by typing @kbd{gc()} at the R prompt.  This may
@c  help you in finding out whether to increase @option{--vsize} or
@c  @option{--nsize}.  Note that following @kbd{gcinfo(TRUE)}, automatic
@c  garbage collection always prints memory use statistics.

@c  As of version 0.62.3, R will tell you whether you ran out of cons or
@c  heap memory.

@c  The defaults for @option{--nsize} and @option{--vsize} can be changed by
@c  setting the environment variables @env{R_NSIZE} and @env{R_VSIZE}
@c  respectively, perhaps most conveniently on Unix in the R environment
@c  file (@file{~/.Renviron} by default).

@c  When using @code{read.table()}, the memory requirements are in fact
@c  higher than anticipated, because the file is first read in as one long
@c  string which is then split again.  Use @code{scan()} if possible in
@c  case you run out of memory when reading in a large table.

@c  R version 1.2.0 introduces a new ``generational'' garbage collector,
@c  which will increase the memory available to R as needed.  The interface
@c  for controlling the generational collector is still experimental and in
@c  flux.  Currently, the command line arguments and environment variables
@c  described above can be used to supply minimal values for the sizes of
@c  the node and vector heaps.

Versions of R prior to 1.2.0 used a @emph{static} memory model.  At
startup, R asked the operating system to reserve a fixed amount of
memory for it.  The size of this chunk could not be changed
subsequently.  Hence, it could happen that not enough memory was
allocated, e.g., when trying to read large data sets into R.  In such
cases, it was necessary to restart R with more memory available, as
controlled by the command line options @option{--nsize} and
@option{--vsize}.

R version 1.2.0 introduces a new ``generational'' garbage collector,
which will increase the memory available to R as needed.  Hence, user
intervention is no longer necessary for ensuring that enough memory is
available.

@node Why does sourcing a correct file fail?, How can I set components of a list to NULL?, Why does R run out of memory?, R Miscellanea
@section Why does sourcing a correct file fail?

Versions of R prior to 1.2.1 may have had problems parsing files not
ending in a newline.  Earlier R versions had a similar problem when
reading in data files.  This should no longer happen.

@c  This can happen for example when Emacs is used for editing the file and
@c  @code{next-line-add-newlines} is set to @code{nil}.  To avoid the
@c  problem, either set @code{require-final-newline} to a non-@code{nil}
@c  value in one of your Emacs startup files, or make sure R-mode (@pxref{Is
@c  there Emacs support for R?}) is used for editing R source files (which
@c  locally ensures this setting).

@node How can I set components of a list to NULL?, How can I save my workspace?, Why does sourcing a correct file fail?, R Miscellanea
@section How can I set components of a list to NULL?

You can use

@smallexample
x[i] <- list(NULL)
@end smallexample

@noindent
to set component @code{i} of the list @code{x} to @code{NULL}, similarly
for named components.  Do not set @code{x[i]} or @code{x[[i]]} to
@code{NULL}, because this will remove the corresponding component from
the list.

For dropping the row names of a matrix @code{x}, it may be easier to use
@code{rownames(x) <- NULL}, similarly for column names.

@node How can I save my workspace?, How can I clean up my workspace?, How can I set components of a list to NULL?, R Miscellanea
@section How can I save my workspace?

@code{save.image()} saves the objects in the user's @code{.GlobalEnv} to
the file @file{.RData} in the R startup directory.  (This is also what
happens after @kbd{q("yes")}.)  Using @code{save.image(@var{file})} one
can save the image under a different name.

@node How can I clean up my workspace?, How can I get eval() and D() to work?, How can I save my workspace?, R Miscellanea
@section How can I clean up my workspace?

To remove all objects in the currently active environment (typically
@code{.GlobalEnv}), you can do

@smallexample
rm(list = ls(all = TRUE))
@end smallexample

@noindent
(Without @option{all = TRUE}, only the objects with names not starting
with a @samp{.} are removed.)

@node How can I get eval() and D() to work?, Why do my matrices lose dimensions?, How can I clean up my workspace?, R Miscellanea
@section How can I get eval() and D() to work?

Strange things will happen if you use @code{eval(print(x), envir = e)}
or @code{D(x^2, "x")}.  The first one will either tell you that
"@code{x}" is not found, or print the value of the wrong @code{x}.
The other one will likely return zero if @code{x} exists, and an error
otherwise.

This is because in both cases, the first argument is evaluated in the
calling environment first.  The result (which should be an object of
mode @code{"expression"} or @code{"call"}) is then evaluated or
differentiated.  What you (most likely) really want is obtained by
``quoting'' the first argument upon surrounding it with
@code{expression()}.  For example,

@smallexample
R> D(expression(x^2), "x")
2 * x
@end smallexample

Although this behavior may initially seem to be rather strange, is
perfectly logical.  The ``intuitive'' behavior could easily be
implemented, but problems would arise whenever the expression is
contained in a variable, passed as a parameter, or is the result of a
function call.  Consider for instance the semantics in cases like

@smallexample
D2 <- function(e, n) D(D(e, n), n)
@end smallexample

@noindent
or

@smallexample
g <- function(y) eval(substitute(y), sys.frame(sys.parent(n = 2)))
g(a * b)
@end smallexample

See the help page for @code{deriv()} for more examples.

@node Why do my matrices lose dimensions?, How does autoloading work?, How can I get eval() and D() to work?, R Miscellanea
@section Why do my matrices lose dimensions?

When a matrix with a single row or column is created by a subscripting
operation, e.g., @code{row <- mat[2, ]}, it is by default turned into a
vector.  In a similar way if an array with dimension, say, @w{2 x 3 x 1
x 4} is created by subscripting it will be coerced into a @w{2 x 3 x 4}
array, losing the unnecessary dimension.  After much discussion this has
been determined to be a @emph{feature}.

To prevent this happening, add the option @option{drop = FALSE} to the
subscripting.  For example,

@smallexample
rowmatrix <- mat[2, , drop = FALSE]  # @r{creates a row matrix}
colmatrix <- mat[, 2, drop = FALSE]  # @r{creates a column matrix}
a <- b[1, 1, 1, drop = FALSE]        # @r{creates a 1 x 1 x 1 array}
@end smallexample

The @option{drop = FALSE} option should be used defensively when
programming.  For example, the statement

@smallexample
somerows <- mat[index, ]
@end smallexample

@noindent
will return a vector rather than a matrix if @code{index} happens to
have length 1, causing errors later in the code.  It should probably be
rewritten as

@smallexample
somerows <- mat[index, , drop = FALSE]
@end smallexample

@node How does autoloading work?, How should I set options?, Why do my matrices lose dimensions?, R Miscellanea
@section How does autoloading work?

R has a special environment called @code{.AutoloadEnv}.  Using
@kbd{autoload(@var{name}, @var{pkg})}, where @var{name} and
@var{pkg} are strings giving the names of an object and the package
containing it, stores some information in this environment.  When R
tries to evaluate @var{name}, it loads the corresponding package
@var{pkg} and reevaluates @var{name} in the new package's
environment.

Using this mechanism makes R behave as if the package was loaded, but
does not occupy memory (yet).

See the help page for @code{autoload()} for a very nice example.

@node How should I set options?, How do file names work in Windows?, How does autoloading work?, R Miscellanea
@section How should I set options?

The function @code{options()} allows setting and examining a variety of
global ``options'' which affect the way in which R computes and displays
its results.  The variable @code{.Options} holds the current values of
these options, but should never directly be assigned to unless you want
to drive yourself crazy---simply pretend that it is a ``read-only''
variable.

For example, given

@smallexample
test1 <- function(x = pi, dig = 3) @{
  oo <- options(digits = dig); on.exit(options(oo));
  cat(.Options$digits, x, "\n")
@}
test2 <- function(x = pi, dig = 3) @{
  .Options$digits <- dig
  cat(.Options$digits, x, "\n")
@}
@end smallexample

@noindent
we obtain:

@smallexample
R> test1()
3 3.14 
R> test2()
3 3.141593
@end smallexample

What is really used is the @emph{global} value of @code{.Options}, and
using @kbd{options(OPT = VAL)} correctly updates it.  Local copies of
@code{.Options}, either in @code{.GlobalEnv} or in a function
environment (frame), are just silently disregarded.

@node How do file names work in Windows?, Why does plotting give a color allocation error?, How should I set options?, R Miscellanea
@section How do file names work in Windows?

As R uses C-style string handling, @samp{\} is treated as an escape
character, so that for example one can enter a newline as @samp{\n}.
When you really need a @samp{\}, you have to escape it with another
@samp{\}.

Thus, in filenames use something like @code{"c:\\data\\money.dat"}.  You
can also replace @samp{\} by @samp{/} (@code{"c:/data/money.dat"}).

@node Why does plotting give a color allocation error?, How do I convert factors to numeric?, How do file names work in Windows?, R Miscellanea
@section Why does plotting give a color allocation error?

Sometimes plotting, e.g., when running @code{demo(image)}, results in
``Error: color allocation error''.  This is an X problem, and only
indirectly related to R.  It occurs when applications started prior to R
have used all the available colors.  (How many colors are available
depends on the X configuration; sometimes only 256 colors can be used.)

One application which is notorious for ``eating'' colors is Netscape.
If the problem occurs when Netscape is running, try (re)starting it with
either the @option{-no-install} (to use the default colormap) or the
@option{-install} (to install a private colormap) option.

You could also set the @code{colortype} of @code{X11()} to
@code{"pseudo.cube"} rather than the default @code{"pseudo"}.  See the
help page for @code{X11()} for more information.

@c  @node Is R Y2K-compliant?, How do I convert factors to numeric?, Why does plotting give a color allocation error?, R Miscellanea
@c  @section Is R Y2K-compliant?

@c  We expect R to be Y2K compliant when compiled and run on a Y2K compliant
@c  system.  In particular R does not internally represent or manipulate
@c  dates as two-digit quantities.  However, no guarantee of Y2K compliance
@c  is provided for R.  R is free software and comes with @emph{no warranty
@c  whatsoever}.

@c  R, like any other programming language, can be used to write programs
@c  and manipulate data in ways that are not Y2K compliant.

@node How do I convert factors to numeric?, Are Trellis displays implemented in R?, Why does plotting give a color allocation error?, R Miscellanea
@section How do I convert factors to numeric?

It may happen that when reading numeric data into R (usually, when
reading in a file), they come in as factors.  If @code{f} is such a
factor object, you can use

@smallexample
as.numeric(as.character(f))
@end smallexample

@noindent
to get the numbers back.  More efficient, but harder to remember, is

@smallexample
as.numeric(levels(f))[as.integer(f)]
@end smallexample

In any case, do not call @code{as.numeric()} or their likes directly.

@node Are Trellis displays implemented in R?, What are the enclosing and parent environments?, How do I convert factors to numeric?, R Miscellanea
@section Are Trellis displays implemented in R?

An R package called @strong{lattice}, which provides graphical
functionality that is compatible with most Trellis commands, is under
development.  The latest version of the package may be downloaded from
the @file{contrib/Devel} area of @acronym{CRAN}.  @strong{lattice}
currently relies on another package called @strong{grid} (also under
development) so you will need to download that as well.  Because these
packages are under active development, they might only work with the
latest development version of R.

You could also look at @code{coplot()} and @code{dotchart()} which might
do at least some of what you want.  Note also that the R version of
@code{pairs()} is fairly general and provides most of the functionality
of @code{splom()}, and that R's default plot method has an argument
@code{asp} allowing to specify (and fix against device resizing) the
aspect ratio of the plot.

(Because the word ``Trellis'' has been claimed as a trademark we do not
use it in R.  The name ``lattice'' has been proposed for the R
equivalent.)

@node What are the enclosing and parent environments?, How can I substitute into a plot label?, Are Trellis displays implemented in R?, R Miscellanea
@section What are the enclosing and parent environments?

Inside a function you may want to access variables in two additional
environments: the one that the function was defined in (``enclosing''),
and the one it was invoked in (``parent'').

If you create a function at the command line or load it in a package its
enclosing environment is the global workspace.  If you define a function
@code{f()} inside another function @code{g()} its enclosing environment
is the environment inside @code{g()}.  The enclosing environment for a
function is fixed when the function is created.  You can find out the
enclosing environment for a function @code{f()} using
@code{environment(f)}.

The ``parent'' environment, on the other hand, is defined when you
invoke a function.  If you invoke @code{lm()} at the command line its
parent environment is the global workspace, if you invoke it inside a
function @code{f()} then its parent environment is the environment
inside @code{f()}.  You can find out the parent environment for an
invocation of a function by using @code{parent.frame()} or
@code{sys.frame(sys.parent())}.

So for most user-visible functions the enclosing environment will be the
global workspace, since that is where most functions are defined.  The
parent environment will be wherever the function happens to be called
from.  If a function @code{f()} is defined inside another function
@code{g()} it will probably be used inside @code{g()} as well, so its
parent environment and enclosing environment will probably be the same.

Parent environments are important because things like model formulas
need to be evaluated in the environment the function was called from,
since that's where all the variables will be available.  This relies on
the parent environment being potentially different with each invocation.

Enclosing environments are important because a function can use
variables in the enclosing environment to share information with other
functions or with other invocations of itself (see the section on
lexical scoping).  This relies on the enclosing environment being the
same each time the function is invoked.

Scoping @emph{is} hard.  Looking at examples helps.  It is particularly
instructive to look at examples that work differently in R and S and try
to see why they differ.  One way to describe the scoping differences
between R and S is to say that in S the enclosing environment is
@emph{always} the global workspace, but in R the enclosing environment
is wherever the function was created.

@node How can I substitute into a plot label?, What are valid names?, What are the enclosing and parent environments?, R Miscellanea
@section How can I substitute into a plot label?

Often, it is desired to use the value of an R object in a plot label,
e.g., a title.  This is easily accomplished using @code{paste()} if the
label is a simple character string, but not always obvious in case the
label is an expression (for refined mathematical annotation).  In such a
case, either use @code{parse()} on your pasted character string or use
@code{substitute()} on an expression.  For example, if @code{ahat} is an
estimator of your parameter @math{a} of interest, use

@smallexample
title(substitute(hat(a) == ahat, list(ahat = ahat)))
@end smallexample

@noindent
(note that it is @samp{==} and not @samp{=}).  There are more worked
examples in the mailing list achives.

@node What are valid names?, Are GAMs implemented in R?, How can I substitute into a plot label?, R Miscellanea
@section What are valid names?

When creating data frames using @code{data.frame()} or
@code{read.table()}, R by default ensures that the variable names are
syntactically valid.  (The argument @option{check.names} to these
functions controls whether variable names are checked and adjusted by
@code{make.names()} if needed.)

To understand what names are ``valid'', one needs to take into account
that the term ``name'' is used in several different (but related) ways
in the language:

@enumerate
@item
A @emph{syntactic name} is a string the parser interprets as this type
of expression.  It consists of letters, numbers, and the dot character
and starts with a letter or the dot.

@item
An @emph{object name} is a string associated with an object that is
assigned in an expression either by having the object name on the left
of an assignment operation or as an argument to the @code{assign()}
function.  It is usually a syntactic name as well, but can be any
non-empty string if it is quoted (and it is always quoted in the call to
@code{assign()}).

@item
An @emph{argument name} is what appears to the left of the equals sign
when supplying an argument in a function call (for example,
@code{f(trim=.5)}).  Argument names are also usually syntactic names,
but again can be anything if they are quoted.

@item
An @emph{element name} is a string that identifies a piece of an object
(a component of a list, for example.)  When it is used on the right of
the @samp{$} operator, it must be a syntactic name, or quoted.
Otherwise, element names can be any strings.  (When an object is used as
a database, as in a call to @code{eval()} or @code{attach()}, the
element names become object names.)

@item
Finally, a @emph{file name} is a string identifying a file in the
operating system for reading, writing, etc.  It really has nothing much
to do with names in the language, but it is traditional to call these
strings file ``names''.
@end enumerate

@node Are GAMs implemented in R?, Why is the output not printed when I source() a file?, What are valid names?, R Miscellanea
@section Are GAMs implemented in R?

There is a @code{gam()} function for Generalized Additive Models in
package @strong{mgcv}, but it is not an exact clone of what is described
in the White Book (no @code{lo()} for example).  Package @strong{gss}
can fit spline-based GAMs too.  And if you can accept regression splines
you can use @code{glm()}.  For gaussian GAMs you can use @code{bruto()}
from package @strong{mda}.

@c <FIXME>
@c Simon Wood <snw@mcs.st-and.ac.uk> says that for GAMs,
@c   You might want to try the packages mgcv, which has a version of
@c   gam(), or gss which will fit a wide range of spline models.
@c Something about this should be added once it is proven to work.
@c </FIXME>

@node Why is the output not printed when I source() a file?, Why does outer() behave strangely with my function?, Are GAMs implemented in R?, R Miscellanea
@section Why is the output not printed when I source() a file?

Most R commands do not generate any output. The command

@smallexample
1+1
@end smallexample

@noindent
computes the value 2 and returns it; the command

@smallexample
summary(glm(y~x+z, family=binomial))
@end smallexample

@noindent
fits a logistic regression model, computes some summary information and
returns an object of class @code{"summary.glm"} (@pxref{How should I
write summary methods?}).

If you type @samp{1+1} or @samp{summary(glm(y~x+z, family=binomial))} at
the command line the returned value is automatically printed (unless it
is @code{invisible()}), but in other circumstances, such as in a
@code{source()}d file or inside a function it isn't printed unless you
specifically print it.

To print the value use

@smallexample
print(1+1)
@end smallexample

@noindent
or

@smallexample
print(summary(glm(y~x+z, family=binomial)))
@end smallexample

@noindent
instead, or use @code{source(@var{file}, echo=TRUE)}.

@node Why does outer() behave strangely with my function?,  , Why is the output not printed when I source() a file?, R Miscellanea
@section Why does outer() behave strangely with my function?

As the help for @code{outer()} indicates, it does not work on arbitrary
functions the way the @code{apply()} family does.  It requires functions
that are vectorized to work elementwise on arrays.  As you can see by
looking at the code, @code{outer(x, y, FUN)} creates two large vectors
containing every possible combination of elements of @code{x} and
@code{y} and then passes this to @code{FUN} all at once.  Your function
probably cannot handle two large vectors as parameters.

If you have a function that cannot handle two vectors but can handle two
scalars, then you can still use @code{outer()} but you will need to wrap
your function up first, to simulate vectorized behavior.  Suppose your
function is

@smallexample
foo <- function(x, y, happy) @{
  stopifnot(length(x) == 1, length(y) == 1) # scalars only!
  (x + y) * happy
@}
@end smallexample

@noindent
If you define the general function

@smallexample
wrapper <- function(x, y, my.fun, ...) @{
  sapply(seq(along=x), FUN = function(i) my.fun(x[i], y[i], ...))
@}
@end smallexample

@noindent
then you can use @code{outer()} by writing, e.g.,

@smallexample
outer(1:4, 1:2, FUN = wrapper, my.fun = foo, happy = 10)
@end smallexample


@node R Programming, R Bugs, R Miscellanea, Top
@chapter R Programming

@menu
* How should I write summary methods?::  
* How can I debug dynamically loaded code?::  
* How can I inspect R objects when debugging?::  
* How can I change compilation flags?::  
@end menu

@node How should I write summary methods?, How can I debug dynamically loaded code?, R Programming, R Programming
@section How should I write summary methods?

Suppose you want to provide a summary method for class @code{foo}.  Then
@code{summary.foo()} should not print anything, but return an object of
class @code{"summary.foo"}, @emph{and} you should write a method
@code{print.summary.foo()} which nicely prints the summary information
and invisibly returns its object.  This approach is preferred over
having @code{summary.foo()} print summary information and return
something useful, as sometimes you need to grab something computed by
@code{summary()} inside a function or similar.  In such cases you don't
want anything printed.

@node How can I debug dynamically loaded code?, How can I inspect R objects when debugging?, How should I write summary methods?, R Programming
@section How can I debug dynamically loaded code?

Roughly speaking, you need to start R inside the debugger, load the
code, send an interrupt, and then set the required breakpoints.

@ifclear UseExternalXrefs
See section ``Finding entry points in dynamically loaded code'' in
@cite{Writing R Extensions}.
@end ifclear
@ifset UseExternalXrefs
@xref{Finding entry points, , Finding entry points in dynamically loaded
code, R-exts, Writing R Extensions}.
@end ifset
This manual is included in the R distribution, @pxref{What documentation
exists for R?}.

@node How can I inspect R objects when debugging?, How can I change compilation flags?, How can I debug dynamically loaded code?, R Programming
@section How can I inspect R objects when debugging?

The most convenient way is to call @code{R_PV} from the symbolic
debugger.

@ifclear UseExternalXrefs
See section ``Inspecting R objects when debugging'' in @cite{Writing R
Extensions}.
@end ifclear
@ifset UseExternalXrefs
@xref{Inspecting R objects, , Inspecting R objects when debugging,
R-exts, Writing R Extensions}.
@end ifset

@node How can I change compilation flags?,  , How can I inspect R objects when debugging?, R Programming
@section How can I change compilation flags?

Suppose you have C code file for dynloading into R, but you want to use
@code{R CMD SHLIB} with compilation flags other than the default ones
(which were determined when R was built).  You could change the file
@file{@env{R_HOME}/etc/Makeconf} to reflect your preferences.  If you
are a Bourne shell user, you can also pass the desired flags to Make
(which is used for controlling compilation) via the Make variable
@code{MAKEFLAGS}, as in

@smallexample
MAKEFLAGS="CFLAGS=-O3" R CMD SHLIB *.c
@end smallexample

@node R Bugs, Acknowledgments, R Programming, Top
@chapter R Bugs

@menu
* What is a bug?::              
* How to report a bug::         
@end menu

@node What is a bug?, How to report a bug, R Bugs, R Bugs
@section What is a bug?

If R executes an illegal instruction, or dies with an operating system
error message that indicates a problem in the program (as opposed to
something like ``disk full''), then it is certainly a bug.  If you call
@code{.C()}, @code{.Fortran()}, @code{.External()} or @code{.Call()} (or
@code{.Internal()}) yourself (or in a function you wrote), you can
always crash R by using wrong argument types (modes).  This is not a
bug.

Taking forever to complete a command can be a bug, but you must make
certain that it was really R's fault.  Some commands simply take a long
time.  If the input was such that you @emph{know} it should have been
processed quickly, report a bug.  If you don't know whether the command
should take a long time, find out by looking in the manual or by asking
for assistance.

If a command you are familiar with causes an R error message in a case
where its usual definition ought to be reasonable, it is probably a bug.
If a command does the wrong thing, that is a bug.  But be sure you know
for certain what it ought to have done.  If you aren't familiar with the
command, or don't know for certain how the command is supposed to work,
then it might actually be working right.  Rather than jumping to
conclusions, show the problem to someone who knows for certain.

Finally, a command's intended definition may not be best for statistical
analysis.  This is a very important sort of problem, but it is also a
matter of judgment.  Also, it is easy to come to such a conclusion out
of ignorance of some of the existing features.  It is probably best not
to complain about such a problem until you have checked the
documentation in the usual ways, feel confident that you understand it,
and know for certain that what you want is not available.  If you are
not sure what the command is supposed to do after a careful reading of
the manual this indicates a bug in the manual.  The manual's job is to
make everything clear.  It is just as important to report documentation
bugs as program bugs.  However, we know that the introductory
documentation is seriously inadequate, so you don't need to report this.

If the online argument list of a function disagrees with the manual, one
of them must be wrong, so report the bug.

@node How to report a bug,  , What is a bug?, R Bugs
@section How to report a bug

When you decide that there is a bug, it is important to report it and to
report it in a way which is useful.  What is most useful is an exact
description of what commands you type, starting with the shell command
to run R, until the problem happens.  Always include the version of R,
machine, and operating system that you are using; type @kbd{version} in
R to print this.

The most important principle in reporting a bug is to report
@emph{facts}, not hypotheses or categorizations.  It is always easier to
report the facts, but people seem to prefer to strain to posit
explanations and report them instead.  If the explanations are based on
guesses about how R is implemented, they will be useless; others will
have to try to figure out what the facts must have been to lead to such
speculations.  Sometimes this is impossible.  But in any case, it is
unnecessary work for the ones trying to fix the problem.

For example, suppose that on a data set which you know to be quite large
the command

@smallexample
R> data.frame(x, y, z, monday, tuesday)
@end smallexample

@noindent
never returns.  Do not report that @code{data.frame()} fails for large
data sets.  Perhaps it fails when a variable name is a day of the week.
If this is so then when others got your report they would try out the
@code{data.frame()} command on a large data set, probably with no day of
the week variable name, and not see any problem.  There is no way in the
world that others could guess that they should try a day of the week
variable name.

Or perhaps the command fails because the last command you used was a
method for @code{"["()} that had a bug causing R's internal data
structures to be corrupted and making the @code{data.frame()} command
fail from then on.  This is why others need to know what other commands
you have typed (or read from your startup file).

It is very useful to try and find simple examples that produce
apparently the same bug, and somewhat useful to find simple examples
that might be expected to produce the bug but actually do not.  If you
want to debug the problem and find exactly what caused it, that is
wonderful.  You should still report the facts as well as any
explanations or solutions.  Please include an example that reproduces
the problem, preferably the simplest one you have found.

Invoking R with the @option{--vanilla} option may help in isolating a
bug.  This ensures that the site profile and saved data files are not
read.

On Unix systems a bug report can be generated using the function
@code{bug.report()}.  This automatically includes the version
information and sends the bug to the correct address.  Alternatively the
bug report can be emailed to @email{r-bugs@@r-project.org} or submitted
to the Web page at @uref{http://bugs.r-project.org/}.

Bug reports on contributed packages should perhaps be sent to the
package maintainer rather than to r-bugs.

@node Acknowledgments,  , R Bugs, Top
@chapter Acknowledgments

Of course, many many thanks to Robert and Ross for the R system, and to
the package writers and porters for adding to it.

Special thanks go to Doug Bates, Peter Dalgaard, Paul Gilbert, Stefano
Iacus, Fritz Leisch, Jim Lindsey, Thomas Lumley, Martin Maechler, Brian
D. Ripley, Anthony Rossini, and Andreas Weingessel for their comments
which helped me improve this @acronym{FAQ}.

More to some soon @dots{}

@bye

@c Local Variables: ***
@c mode: TeXinfo ***
@c End: ***
