\input texinfo
@c %**start of header
@setfilename R-FAQ.info
@settitle R FAQ
@paragraphindent 0
@c %**end of header

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

@finalout

@include R-defs.texi

@c <FIXME>
@c Getting FAQ_YEAR from version.texi causes too much trouble for now,
@c as making ${top_builddir}/doc/FAQ in front-matter is done ahead of
@c building version.texi (which in turn currently needs having built R)
@c as it uses R_EXE to compute RWVERSION.
@c Need to revisit more generally whether we still want the front-matter
@c things.
@c For now, simply hard-wire the year again.
@c @include version.texi
@set FAQ_YEAR 2024
@c </FIXME>

@macro CRAN{}
@acronym{CRAN}
@end macro

@macro FORTRAN{}
FORTRAN
@end macro

@macro XML{}
@acronym{XML}
@end macro

@macro XSL{}
@acronym{XSL}
@end macro

@macro doi {d}
doi:@tie{}@url{https://doi.org/\d\, \d\}
@end macro

@titlepage
@title R @acronym{FAQ}
@subtitle Frequently Asked Questions on R
@author @I{Kurt Hornik}
@author and the R Core Team
@end titlepage

@ifinfo
@c We do not really see this in info, but in plain text output.
R FAQ                            @*
Frequently Asked Questions on R  @*
@I{Kurt Hornik} and the R Core Team  @*

@sp 2
@end ifinfo

@c @ifnothtml
@contents
@c @end ifnothtml

@ifnottex
@node Top
@top R FAQ
@c @ifhtml
@c @html
@c <h2>Frequently Asked Questions on R</h2>
@c <h3 style="text-align: center;">Kurt Hornik and the R Core Team</h3>
@c <hr/>
@c @end html
@c @end ifhtml

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



@node Introduction
@chapter Introduction


@node Legalese
@section Legalese

Copyright @copyright{} 1998--2020 @I{Kurt Hornik} @*
@Rcopyright{2021}

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
@I{MERCHANTABILITY} or FITNESS FOR A PARTICULAR PURPOSE.  See the
@acronym{GNU} General Public License for more details.

Copies of the @acronym{GNU} General Public License versions are
available at

@display
@url{https://www.R-project.org/Licenses/}
@end display

@node Obtaining this document
@section Obtaining this document

The latest version of this document is always available from

@display
@url{https://CRAN.R-project.org/doc/manuals/}
@end display

From there, you can obtain versions converted to
@url{https://CRAN.R-project.org/doc/manuals/R-FAQ.html,, @HTML{}} and
@url{https://CRAN.R-project.org/doc/manuals/R-FAQ.pdf,, PDF}.

@node Citing this document
@section Citing this document

In publications, please refer to this @acronym{FAQ} as @I{Hornik} and R Core Team
(@value{FAQ_YEAR}), ``The R @acronym{FAQ}'', and give the above,
@emph{official} @acronym{URL}:

@example
@group
@@Misc@{,
  author        = @{Kurt Hornik and the R Core Team@},
  title         = @{@{R@} @{FAQ@}@},
  year          = @{@value{FAQ_YEAR}@},
  url           = @{https://CRAN.R-project.org/doc/manuals/R-FAQ.html@}
@}
@end group
@end example

@node Notation
@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
@section Feedback

Feedback via email to @email{R-devel@@R-project.org} is most welcome.

Features specific to the Windows and macOS ports of R are
described in the
@url{https://CRAN.R-project.org/bin/windows/base/rw-FAQ.html, ``R for
Windows @acronym{FAQ}''} and the
@url{https://CRAN.R-project.org/bin/macosx/RMacOSX-FAQ.html, ``R for Mac
OS X @acronym{FAQ}''}.  If you have information on Mac or Windows
systems that you think should be added to this document, please let us
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
@chapter R Basics


@node What is R?
@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 & @I{Wilks}' S (@pxref{What is S?}) and @I{Sussman}'s
@url{http://community.schemewiki.org/?scheme-faq, 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, @I{Ross Ihaka}}
and @email{Robert.Gentleman@@R-project.org, @I{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 archive, currently consisting of
@display
@I{John Chambers},
@I{Peter Dalgaard},
@I{Robert Gentleman},
@I{Kurt Hornik},
@I{Ross Ihaka},
@I{Tomas Kalibera},
@I{Michael Lawrence},
@I{Uwe Ligges},
@I{Thomas Lumley},
@I{Martin Maechler},
@I{Sebastian Meyer},
@I{Paul Murrell},
@I{Martyn Plummer},
@I{Brian Ripley},
@I{Deepayan Sarkar},
@I{Duncan Temple Lang},
@I{Luke Tierney}, and 
@I{Simon Urbanek},
@end display
@noindent
plus 
@I{Heiner Schwarte} up to October 1999, 
@I{Guido Masarotto} up to June 2003, 
@I{Stefano Iacus} up to July 2014, 
@I{Seth Falcon} up to August 2015, 
@I{Duncan Murdoch} up to September 2017, 
@I{Martin Morgan} up to June 2021,
@I{Douglas Bates} up to March 2024, and 
@I{Friedrich Leisch} up to April 2024.

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

@node What machines does R run on?
@section What machines does R run on?

R is being developed for the Unix-like, Windows and Mac families of
operating systems.  Support for Mac OS Classic ended with R 1.7.1.

The current version of R will configure and build under a number of
common Unix-like (e.g., @uref{https://en.wikipedia.org/wiki/Unix-like})
platforms including @var{cpu}-linux-gnu for the @I{i386},
@I{amd64}/@I{x86_64}, @I{alpha}, @I{arm}, @I{arm64}, @I{hppa},
@I{mips}/@I{mipsel}, @I{powerpc}, @I{s390x} and @I{sparc}
@acronym{CPU}s (e.g.,
@url{https://buildd.debian.org/build.php?&pkg=r-base}), 
@I{386-hurd-gnu},
@var{cpu}-@I{kfreebsd}-gnu for @I{i386} and @I{amd64},
@c <FIXME>
@c Not sure anymore ...
@c alpha-dec-osf4,
@c <COMMENT>
@c i386-freebsd reported by B. Gian James" <gian.james@gmail.com> on
@c 2009-01-11
@c (Architecture: i386, OS: FreeBSD 7.1-PRERELEASE, Vendor: PC-BSD)
@c i386-freebsd,
@c but all recent reports are on x86_64
@c </COMMENT>
@c hppa-hp-hpux, 
@c mips-sgi-irix,
@c </FIXME>
@I{i386-pc-solaris},
@I{rs6000-ibm-aix},
@I{sparc-sun-solaris}, 
@I{x86_64-apple-darwin},
@I{aarch64-apple-darwin}, 
@I{x86_64-unknown-freebsd} and 
@I{x86_64-unknown-openbsd}.

@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?
@section What is the current version of R?
 
R uses a `major.minor.patchlevel' numbering scheme.  Based on this,
there are the current release version of R (`r-release') as well as two
development versions of R, a patched version of the current release
(`r-patched') and one working towards the next minor or eventually major
(`r-devel') releases of R, respectively.  New features are typically
introduced in r-devel, while r-patched is for bug fixes mostly.

See @url{https://CRAN.R-project.org/sources.html} for the current
versions of r-release, r-patched and r-devel.

@node How can R be obtained?
@section How can R be obtained?

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

Sources are also available via @url{https://svn.R-project.org/R/}, the
R Subversion repository, but currently not via anonymous @I{rsync} (nor
CVS).

Tarballs with daily snapshots of the r-devel and r-patched development
versions of R can be found at
@url{https://cran.r-project.org/src/base-prerelease/}. An alternative
source is
@url{https://stat.ethz.ch/R/daily/}.

@c Sources are also available via anonymous rsync.  Use

@c @example
@c rsync -rptC --delete rsync.R-project.org::@var{module} R
@c @end example

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

@c @c <NOTE>
@c @c Keep in sync with R-admin.
@c Note that the sources available via rsync do not include the recommended
@c packages, whereas these are included in the tarballs of released
@c versions.  To install the appropriate sources for the recommended
@c packages, run @command{./tools/rsync-recommended} from the top-level of
@c the R sources that you pulled by rsync.
@c @c </NOTE>

@c The sources of the development version are also available via anonymous
@c CVS.  See @url{http://anoncvs.R-project.org} for more information.

@node How can R be installed?
@section How can R be installed?

@node How can R be installed (Unix-like)
@subsection How can R be installed (Unix-like)

If R is already installed, it can be started by typing @kbd{R} at the
shell prompt (of course, provided that the executable is in your path).

If binaries are available for your platform (see @ref{Are there
Unix-like 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-like 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{} 90 compiler as well as a C compiler to
build R.

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

@example
$ ./configure
$ make
@end example

If these commands execute successfully, the R binary and a shell script
front-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,
@HTML{} versions of the R manuals (e.g., @file{R-exts.html}, the
``Writing R Extensions'' manual) are built in the @file{doc/manual}
subdirectory (if a suitable @command{texi2any} program was found).

Use @kbd{make pdf} to build PDF (Portable Document Format)
versions of the R manuals, including
@file{fullrefman.pdf} (an R object reference index).  Manuals written in the
@acronym{GNU} @I{Texinfo} system can also be converted to @file{.info} files
suitable for reading online with Emacs or stand-alone @acronym{GNU}
Info; use @kbd{make info} to create these files.

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

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

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

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

@node How can R be installed (Windows)
@subsection How can R be installed (Windows)

The @file{bin/windows} directory of a @CRAN{} site contains binaries for
a base distribution and add-on packages from @CRAN{} to run on 64-bit
versions of Windows 7 and later on x86_64 chips (R 4.1.3 was the last
version of R to support 32-bit Windows).  The Windows version of R was
created by @I{Robert Gentleman} and @I{Guido Masarotto}; @I{Brian
Ripley} and @I{Duncan Murdoch} made substantial contributions and it is
now being maintained by other members of the R Core team.

The same directory has links to snapshots of the r-patched and r-devel
versions of R.

See the @url{https://CRAN.R-project.org/bin/windows/base/rw-FAQ.html,
``R for Windows @acronym{FAQ}''} for more details.

@node How can R be installed (Mac)
@subsection How can R be installed (Mac)

The @file{bin/macosx} directory of a @CRAN{} site contains a standard
Apple installer package to run on macOS 10.13 (`High Sierra') or later,
and another which runs only on `Apple Silicon' Macs under macOS 11
(`@I{Big Sur}') or later.  Once downloaded and executed, the installer will
install the current release of R and R.app, the macOS @acronym{GUI}.
This port of R for macOS is maintained by
@email{Simon.Urbanek@@R-project.org, @I{Simon Urbanek}} (and previously by
@I{Stefano Iacus}).  The
@url{https://CRAN.R-project.org/bin/macosx/RMacOSX-FAQ.html, ``R for
macOS @acronym{FAQ}''} has more details.

Snapshots of the r-patched and r-devel versions of R are available as
Apple installer packages at @uref{https://mac.R-project.org}.


@node Are there Unix-like binaries for R?
@section Are there Unix-like binaries for R?

Binary distributions of R are available on many Unix-like OSes: only
some can be mentioned here so check your OS's search facilities to see
if one is available for yours.

The @file{bin/linux} directory of a @CRAN{} site contains R packages for
Debian and Ubuntu.

Debian packages, maintained by @I{Dirk Eddelbuettel}, have long been part of
the Debian distribution, and can be accessed through APT, the Debian
package maintenance tool.  Use e.g.@: @code{apt-get install r-base
r-recommended} to install the R environment and recommended packages.
If you also want to build R packages from source, also run @code{apt-get
install r-base-dev} to obtain the additional tools required for this.
So-called ``backports'' of the current R packages for at least the
@dfn{stable} distribution of Debian are provided by @I{Johannes Ranke}, and
available from @CRAN{}.  See
@url{https://CRAN.R-project.org/bin/linux/debian/index.html} for details on R
Debian packages and installing the backports, which should also be
suitable for other Debian derivatives.  Native backports for Ubuntu are
provided by @I{Michael Rutter}, see
@url{https://CRAN.R-project.org/bin/linux/ubuntu/index.html} for
instructions.

R binaries for Fedora, maintained by @I{Tom ``Spot'' Callaway} and
@I{Iñaki Ucar}, are provided as part of the Fedora distribution and can
be accessed through @command{dnf}, the @abbr{RPM} installer/updater.
The Fedora R @abbr{RPM} is a ``meta-package'' which installs all the
user and developer components of R (available separately as
@code{R-core} and @code{R-core-devel}), as well as @code{R-java} and
@code{R-java-devel}, which ensures that R is configured for use with
Java.  The R @abbr{RPM} also installs the standalone R math library
(@code{libRmath} and @code{libRmath-devel}), although this is not
necessary to use R.  When a new version of R is released, there may be a
delay of up to 2 weeks until the Fedora @abbr{RPM} becomes publicly
available, as it must pass through the Fedora update process.
The Extra Packages for Enterprise Linux (@abbr{EPEL}) project
(@url{https://docs.fedoraproject.org/en-US/epel/}) provides ports of the
Fedora @abbr{RPM}s for @I{RedHat Enterprise Linux} and compatible
distributions (e.g., @I{CentOS Stream}, @I{Scientific Linux}, @I{Oracle
Linux}, @I{AlmaLinux}, or @I{Rocky Linux} among others).
@abbr{RPM}s for selection of R packages are also provided by Fedora.
Additional @abbr{RPM}s for R packages are maintained by @I{Iñaki Ucar}
on @I{Fedora Copr}.  See @url{https://CRAN.R-project.org/bin/linux/fedora/}
for further details and installation instructions.

No other binary distributions are currently publicly available via
@CRAN{}.

@node What documentation exists for R?
@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
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
@LaTeX{}, see @ref{How can R be installed?}.  An up-to-date @HTML{}
version is always available for web browsing at
@url{https://stat.ethz.ch/R-manual/}.

@c Printed copies of the R reference manual for some version(s) are
@c available from Network Theory Ltd, at
@c @c https: is untrusted
@c @url{http://www.network-theory.co.uk/R/base/}.  For each set of manuals
@c sold, the publisher donates USD 10 to the R Foundation (@pxref{What is
@c the R Foundation?}).

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 @I{Bill Venables} and @I{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 ``@I{Kernighan} & @I{Ritchie} of R'', explains
evaluation, parsing, object oriented programming, computing on the
language, and so forth.
@item ``R Installation and Administration'' (@file{R-admin}).
@item ``R Internals'' (@file{R-ints})
is a guide to R's internal structures.
(Added in R 2.4.0.)
@end itemize

An annotated bibliography (Bib@TeX{} format) of R-related publications
can be found at

@display
@url{https://www.R-project.org/doc/bib/R.bib}
@end display

Books on R by R Core Team members include

@quotation
@I{John M. Chambers} (2008),
``Software for Data Analysis: Programming with R''.  
@I{Springer}, New York, ISBN 978-0-387-75935-7,
@url{https://johnmchambers.su.domains/Rbook/}.

@I{Peter Dalgaard} (2008),
``Introductory Statistics with R'',
@I{2nd} edition.
@I{Springer}, ISBN 978-0-387-79053-4,
@url{http://publicifsv.sund.ku.dk/~pd/ISwR.html}.

@I{Robert Gentleman} (2008),
``R Programming for @I{Bioinformatics}''.
@I{Chapman & Hall/CRC}, @I{Boca Raton}, FL, ISBN 978-1-420-06367-7,
@url{https://bioconductor.org/help/publications/books/r-programming-for-bioinformatics/}.

@I{Stefano M. Iacus} (2008),
``Simulation and Inference for Stochastic Differential Equations: With R
Examples''.
@I{Springer}, New York, ISBN 978-0-387-75838-1.

@I{Deepayan Sarkar} (2007),
``Lattice: Multivariate Data Visualization with R''.
@I{Springer}, New York, ISBN 978-0-387-75968-5.

@I{W. John Braun} and @I{Duncan J. Murdoch} (2007),
``A First Course in Statistical Programming with R''.
 Cambridge University Press, Cambridge, ISBN 978-0521872652.

@I{P. Murrell} (2005), ``R Graphics'',
@I{Chapman & Hall/CRC}, ISBN 1-584-88486-X,
@url{https://www.stat.auckland.ac.nz/~paul/RGraphics/rgraphics.html}.

@I{William N. Venables} and @I{Brian D. Ripley} (2002),
``Modern Applied Statistics with S'' (@I{4th} edition).
@I{Springer}, ISBN 0-387-95457-0,
@url{https://www.stats.ox.ac.uk/pub/MASS4/}.

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

Last, but not least, Ross' and Robert's experience in designing and
implementing R is described in @I{Ihaka} & @I{Gentleman} (1996), 
``R: A Language for Data Analysis and Graphics'', 
@emph{Journal of Computational and Graphical Statistics}, @strong{5}, 299--314
(@doi{10.1080/10618600.1996.10474713}).

@node Citing R
@section Citing R

To cite R in publications, use

@example
@group
@@Manual@{,
  title        = @{R: A Language and Environment for Statistical
                  Computing@},
  author       = @{@{R Core Team@}@},
  organization = @{R Foundation for Statistical Computing@},
  address      = @{Vienna, Austria@},
  year         = @var{YEAR},
  url          = @{https://www.R-project.org@}
@}
@end group
@end example
@noindent
where @var{YEAR} is the release year of the version of R used and can
determined as @code{R.version$year}.

Citation strings (or Bib@TeX{} entries) for R and R packages can also be
obtained by @code{citation()}.

@node What mailing lists exist for R?
@section What mailing lists exist for R?

Thanks to @email{Martin.Maechler@@R-project.org, Martin Maechler}, there
are several mailing lists devoted to R, including the following:

@table @code
@item R-announce
A moderated list for major announcements about the development of R and
the availability of new code.
@item R-packages
A moderated list for announcements on the availability of new or
enhanced contributed packages.
@item R-help
The `main' R mailing list, for discussion about problems and solutions
encountered using R, including using R packages in the standard R distribution 
and on CRAN;  announcements (not covered by `R-announce' or `R-packages'); 
the availability of new functionality for R and documentation of R; 
and for posting nice examples and benchmarks. 
@c about the development of R and the availability of new code.
@c enhancements and patches to the source code and documentation of R,
@c comparison and compatibility with S and @SPLUS{}, and for the posting of
@c nice examples and benchmarks.
@item R-devel
This list is for questions and discussion about code development in R.
@c discussions about the future of R, proposals of new functionality, and
@c pre-testing of new versions.  It is meant for those who maintain an
@c active position in the development of R.
@item R-package-devel
A list which provides a forum for those developing R packages.
@end table

@noindent
Please read the @url{https://www.R-project.org/posting-guide.html,
posting guide} @emph{before} sending anything to any mailing list.

Note in particular that R-help is intended to be comprehensible to
people who want to use R to solve problems but who are not necessarily
interested in or knowledgeable about programming.  Questions likely to
prompt discussion unintelligible to non-programmers (e.g., questions
involving C or C++) should go to R-devel.

Convenient access to information on these lists, subscription, and
archives is provided by the web interface at
@url{https://stat.ethz.ch/mailman/listinfo/}.  One can also subscribe
(or unsubscribe) via email, e.g.@: to R-help by sending @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}.

Send email to @email{R-help@@lists.R-project.org} to send a message to
everyone on the R-help mailing list.  Subscription and posting to the
other lists is done analogously, with @samp{R-help} replaced by
@samp{R-announce}, @samp{R-packages}, and @samp{R-devel}, respectively.
Note that the R-announce and R-packages lists are gatewayed into R-help.
Hence, you should subscribe to either of them only in case you are not
subscribed to R-help.

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.

See @url{https://www.R-project.org/mail.html} for more information on
the R mailing lists.

@c >> No longer want such comments and reports addressed to R-core :
@c The R Core Team can be reached at @email{R-core@@lists.R-project.org}
@c for comments and reports.

@c <FIXME>
@c As of 2017-10, accessing GMANE's gmane.comp.lang.r still says
@c   Not all of Gmane is back yet ...
@c Hence comment out for the time being.
@c Many of the R project's mailing lists are also available via
@c @url{http://gmane.org, Gmane}, from which they can be read with a web
@c browser, using an NNTP news reader, or via RSS feeds.  See
@c @uref{http://dir.gmane.org/index.php?prefix=gmane.comp.lang.r.}@: for
@c the available mailing lists, and @uref{http://www.gmane.org/rss.php} for
@c details on RSS feeds.
@c </FIXME>

@node What is CRAN?
@section What is @acronym{CRAN}?

The ``Comprehensive R Archive Network'' (@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 @CRAN{} main site at WU (@I{Wirtschaftsuniversit@"at Wien}) in Austria
can be found at the @acronym{URL}

@quotation
@c @multitable @columnfractions .45 .30
@c @item
@url{https://CRAN.R-project.org/}
@c @tab (Austria)
@c @end multitable
@end quotation

@noindent
and is mirrored daily to many sites around the world.
See @url{https://CRAN.R-project.org/mirrors.html} for a complete list of
mirrors.  Please use the @CRAN{} site closest to you to reduce network
load.

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

Since March 2016, ``old'' material is made available from a central
@CRAN{} archive server (@url{https://CRAN-archive.R-project.org/}).

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

@node Can I use R for commercial purposes?
@section Can I use R for commercial purposes?

R is released under the
@url{https://www.gnu.org/licenses/old-licenses/gpl-2.0.html,,
@acronym{GNU} General Public License (@acronym{GPL}), version 2 or
version 3}.  If you have any questions regarding the legality of using R
in any particular situation you should bring it up with your legal
counsel.  We are in no position to offer legal advice.

It is the opinion of the R Core Team that one can use R for commercial
purposes (e.g., in business or in consulting).  The @acronym{GPL}, like
all Open Source licenses, permits all and any use of the package.  It
only restricts distribution of R or of other programs containing code
from R.  This is made clear in clause 6 (``No Discrimination Against
Fields of Endeavor'') of the
@url{https://opensource.org/osd, Open Source Definition}:

@quotation
The license must not restrict anyone from making use of the program in a
specific field of endeavor.  For example, it may not restrict the
program from being used in a business, or from being used for genetic
research.
@end quotation

@noindent
It is also explicitly stated in clause 0 of the GPL, which says in part

@quotation
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of running
the Program is not restricted, and the output from the Program is
covered only if its contents constitute a work based on the Program.
@end quotation

Most add-on packages, including all recommended ones, also explicitly
allow commercial use in this way.  A few packages are restricted to
``non-commercial use''; you should contact the author to clarify whether
these may be used or seek the advice of your legal counsel.

None of the discussion in this section constitutes legal advice.  The R
Core Team does not provide legal advice under any circumstances.

@node Why is R named R?
@section Why is R named R?

The name is partly based on the (first) names of the first two R authors
(@I{Robert Gentleman} and @I{Ross Ihaka}), and partly a play on the name of the
Bell Labs language `S' (@pxref{What is S?}).

@c At the time the name was coined no one expected that the software would
@c get used outside of Auckland, so it seemed ok to make a joke of it.

@node What is the R Foundation?
@section What is the R Foundation?

The R Foundation is a not for profit organization working in the public
interest.  It was founded by the members of the R Core Team in order to
provide support for the R project and other innovations in statistical
computing, provide a reference point for individuals, institutions or
commercial enterprises that want to support or interact with the R
development community, and to hold and administer the copyright of R
software and documentation.  See
@url{https://www.R-project.org/foundation/} for more information.

@node What is R-Forge?
@section What is R-Forge?

R-Forge (@url{https://R-Forge.R-project.org/}) offers a central platform
for the development of R packages, R-related software and further
projects.  It is based on @url{https://en.wikipedia.org/wiki/GForge, GForge} offering
easy access to the best in SVN, daily built and checked packages,
mailing lists, bug tracking, message boards/forums, site hosting,
permanent file archival, full backups, and total web-based
administration.  For more information, see the R-Forge web page and
@I{Stefan Theu@ss{}l} and @I{Achim Zeileis} (2009), ``Collaborative software
development using R-Forge'', @url{https://journal.R-project.org/, ,
@emph{The R Journal}}, @strong{1}(1):9--14.



@node R and S
@chapter R and S


@node What is 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
(@abbr{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
@I{Richard A. Becker} and @I{John M. Chambers} (1984),
``S.  An Interactive Environment for Data Analysis and Graphics,''
Monterey: @I{Wadsworth and Brooks/Cole}.

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

@item
@I{Richard A. Becker}, @I{John M. Chambers} and @I{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
@I{John M. Chambers} and @I{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
@I{John M. Chambers} (1998), 
``Programming with Data,''
New York: @I{Springer},
ISBN 0-387-98503-4
(@url{https://johnmchambers.su.domains/Sbook/}).

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

See @url{https://johnmchambers.su.domains/papers/96.7.ps}
for further information on the ``Evolution of the S Language''.

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

@c The @url{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?
@section What is @sc{S-Plus}?

@SPLUS{} is a value-added version of S sold by
@url{https://www.tibco.com/, TIBCO Software Inc} as `@I{TIBCO Spotfire S+}'.
See @url{https://en.wikipedia.org/wiki/S-PLUS} for more information.

@node What are the differences between 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 @emph{engines}.

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


@node Lexical scoping
@subsection Lexical scoping

Contrary to other implementations of the S language, R has adopted an
evaluation model in which nested function definitions are lexically
scoped.  This is analogous to the evaluation model in 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).  In S, the
values of free variables are determined by a set of global variables
(similar to C, there is only local and global scope).  In R, they are
determined by the environment in which the function was created.

Consider the following function:

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

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

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

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

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

@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 @example
@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 example

@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 @example
@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 example

@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 @I{@math{r}-th} order
statistic from a sample of size @math{n} from a (continuous)
distribution.  For simplicity, we shall use both the distribution and
density functions distribution as explicit arguments.  (Example compiled
from various postings by @I{Luke Tierney}.)

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

@example
@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 example

@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

@example
@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 example

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

However, in R there is a much easier solution:

@example
@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 example

@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''):

@example
@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 example

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

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

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

@example
@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 example

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.

Nested lexically scoped functions allow using function closures and
maintaining local state.  A simple example (taken from Abelson and
@I{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 @I{Robert Gentleman} and @I{Ross Ihaka} (2000), ``Lexical
Scope and Statistical Computing'',
@emph{Journal of
Computational and Graphical Statistics}, @strong{9}, 491--508
(@doi{10.1080/10618600.2000.10474895}).

Nested lexically scoped functions also imply 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
piece of memory and uses it to store the objects.  R performs its own
memory management of this piece of memory, growing and shrinking its
size as needed.  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 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
@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 @abbr{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.
@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
@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.  Unless @option{--no-environ}
was given on the command line, R searches for site and user files to
process for setting environment variables.  Then, R searches for a
site-wide startup profile unless the command line option
@option{--no-site-file} was given.  This code is loaded in package
@pkg{base}.  Then, unless @option{--no-init-file} was given, R
searches for a user profile file, 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-data} or
@option{--no-restore} were specified).  Next, a function @code{.First()}
is run if found on the search path.  Finally, function @code{.First.sys}
in the @pkg{base} package is run.  When terminating an R session, by
default a function @code{.Last} is run if found on the search path,
followed by @code{.Last.sys}.  If needed, the functions @code{.First()}
and @code{.Last()} should be defined in the appropriate startup
profiles.  See the help pages for @code{.First} and @code{.Last} for
more details.

@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 objects}, 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

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

@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 @I{Helmert} ones.  This is a deliberate difference reflecting the
opinion that treatment contrasts are more natural.

@item
In R, the argument of a replacement function which corresponds to the
right hand side must be named @samp{value}.  E.g., @code{f(a) <- b} is
evaluated as @code{a <- "f<-"(a, value = b)}.  S always takes the last
argument, irrespective of its name.

@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 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.

@item
In R, the string @code{"NA"} is not treated as a missing value in a
character variable.  Use @code{as.character(NA)} to create a missing
character value.

@item
R disallows repeated formal arguments in function calls.

@item
In S, @code{dump()}, @code{dput()} and @code{deparse()} are essentially
different interfaces to the same code.  In R from version 2.0.0, this is
only true if the same @code{control} argument is used, but by default it
is not.  By default @code{dump()} tries to write code that will evaluate
to reproduce the object, whereas @code{dput()} and @code{deparse()}
default to options for producing deparsed code that is readable.

@item
In R, indexing a vector, matrix, array or data frame with @code{[} using
a character vector index looks only for exact matches (whereas @code{[[}
and @code{$} allow partial matches).  In S, @code{[} allows partial
matches.

@item
S has a two-argument version of @code{atan} and no @code{atan2}.  A call 
in S such as @code{atan(x1, x2)} is equivalent to R's @code{atan2(x1, 
x2)}.  However, beware of named arguments since S's @code{atan(x = a, y
= b)} is equivalent to R's @code{atan2(y = a, x = b)} with the meanings
of @code{x} and @code{y} interchanged.  (R used to have undocumented
support for a two-argument @code{atan} with positional arguments, but
this has been withdrawn to avoid further confusion.)

@item
Numeric constants with no fractional and exponent (i.e., only integer)
part are taken as integer in @SPLUS{} 6.x or later, but as double in R.

@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?
@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 
@I{Paul Murrell} and @I{Ross Ihaka} (2000),
``An Approach to Providing Mathematical Annotation in Plots'', 
@emph{Journal of Computational and Graphical Statistics}, @strong{9}, 582--599
(@doi{10.1080/10618600.2000.10474900}).

@node What is R-plus?
@section What is R-plus?

For a very long time, there was no such thing.

@c This seems gone as of 2019-10.
@c @url{http://www.xlsolutions-corp.com/, XLSolutions Corporation} is
@c currently beta testing a commercially supported version of R named R+
@c (read R plus).

Revolution Analytics has released @I{REvolution R}, now available as
Microsoft R (see
@url{https://blog.revolutionanalytics.com/2016/01/microsoft-r-open.html}
for more information).

@c Now archived at <http://archive.today/WrgxY>
@c @url{http://www.random-technologies-llc.com/, Random Technologies}
@c offers @url{http://random-technologies-llc.com/products/RStat/rstat,
@c RStat}, an enterprise-strength statistical computing environment which
@c combines R with enterprise-level validation, documentation, software
@c support, and consulting services, as well as related R-based products.

See also
@url{https://en.wikipedia.org/wiki/R_programming_language#Commercialized_versions_of_R}
for pointers to commercialized versions of R.



@node R Web Interfaces
@chapter R Web Interfaces

Please refer to the @CRAN{} task view on ``Web Technologies and
Services'' (@url{https://CRAN.R-project.org/view=WebTechnologies}),
specifically section ``Web and Server Frameworks'', for up-to-date
information on R web interface packages.

Early references on R web interfaces include
@I{Jeff Banfield} (1999),
``@I{Rweb}: Web-based Statistical Analysis''
(@doi{10.18637/jss.v004.i01}),
@I{David Firth} (2003),
``@I{CGIwithR}: Facilities for processing web forms using R''
(@doi{10.18637/jss.v008.i10}),
and
@I{Angelo Mineo} and @I{Alfredo Pontillo} (2006),
``Using R via PHP for Teaching Purposes: @I{R-php}''
(@doi{10.18637/jss.v017.i04}).



@node R Add-On Packages
@chapter R Add-On Packages


@node Which add-on packages exist for R?
@section Which add-on packages exist for R?


@node Add-on packages in R
@subsection Add-on packages in R

The R distribution comes with the following packages:

@table @pkg
@c <FIXME>
@c 3.0.0
@item base
Base R functions (and datasets before R 2.0.0).
@item compiler
R byte code compiler (added in R 2.13.0).
@item datasets
Base R datasets (added in R 2.0.0).
@item grDevices
Graphics devices for base and grid graphics (added in R 2.0.0).
@c </FIXME>
@item graphics
R functions for base graphics.
@item grid
A rewrite of the graphics layout capabilities, plus some support for
interaction.
@item methods
Formally defined methods and classes for R objects, plus other
programming tools, as described in the Green Book.
@item parallel
Support for parallel computation, including by forking and by sockets, 
and random-number generation (added in R 2.14.0).
@item splines
Regression spline functions and classes.
@item stats
R statistical functions.
@item stats4
Statistical functions using S4 classes.
@item tcltk
Interface and language bindings to Tcl/Tk @acronym{GUI} elements.
@item tools
Tools for package development and administration.
@item utils
R utility functions.
@end table
@c These ``base packages'' were substantially reorganized in R 1.9.0.  The
@c former @pkg{base} was split into the four packages @pkg{base},
@c @pkg{graphics}, @pkg{stats}, and @pkg{utils}.  Packages @pkg{ctest},
@c @pkg{eda}, @pkg{modreg}, @pkg{mva}, @pkg{nls}, @pkg{stepfun} and
@c @pkg{ts} were merged into @pkg{stats}, package @pkg{lqs} returned to the
@c recommended package @CRANpkg{MASS}, and package @pkg{mle} moved to
@c @pkg{stats4}.

@node Add-on packages from CRAN
@subsection Add-on packages from @acronym{CRAN}

The @CRAN{} @file{src/contrib} area contains a wealth of add-on
packages, including the following @emph{recommended} packages which are
to be included in all binary distributions of R.

@c <FIXME>
@c 3.0.0
@table @pkg
@item KernSmooth
Functions for kernel smoothing (and density estimation) corresponding to
the book ``Kernel Smoothing'' by @I{M. P. Wand} and @I{M. C. Jones}, 1995.
@item MASS
Functions and datasets from the main package of @I{Venables} and @I{Ripley},
``Modern Applied Statistics with S''.
@c (Contained in the @file{VR} bundle for R versions prior to 2.10.0.)
@item Matrix
Support for spares and dense matrices
@c (Recommended for R 2.9.0 or later.)
@item boot
Functions and datasets for bootstrapping from the book ``Bootstrap
Methods and Their Applications'' by @I{A. C. Davison} and @I{D. V. Hinkley},
1997, Cambridge University Press.
@item class
Functions for classification (@math{k}-nearest neighbor and @abbr{LVQ}).
@c (Contained in the @file{VR} bundle for R versions prior to 2.10.0.)
@item cluster
Functions for cluster analysis.
@item codetools
Code analysis tools.
@c (Recommended for R 2.5.0 or later.)
@item foreign
Functions for reading and writing data stored by statistical software
like @I{Minitab}, S, SAS, SPSS, @I{Stata}, @I{Systat}, etc.
@item lattice
Lattice graphics, an implementation of Trellis Graphics functions.
@item mgcv
Routines for GAM@w{s} and other generalized ridge regression problems with
multiple smoothing parameter selection by GCV or @abbr{UBRE}.
@item nlme
Fit and compare Gaussian linear and nonlinear mixed-effects models.
@item nnet
Software for single hidden layer perceptrons (``feed-forward neural
networks''), and for multinomial log-linear models.
@c (Contained in the @file{VR} bundle for R versions prior to 2.10.0.)
@item rpart
Recursive @I{PARTitioning} and regression trees.
@item spatial
Functions for kriging and point pattern analysis from ``Modern Applied
Statistics with S'' by @I{W. Venables} and @I{B. Ripley}.
@c (Contained in the @file{VR} bundle for R versions prior to 2.10.0.)
@item survival
Functions for survival analysis, including penalized likelihood.
@end table
@c </FIXME>
See the @url{https://CRAN.R-project.org/web/packages/, , @CRAN{}
contributed packages page} for more information.

Many of these packages are categorized into
@url{https://CRAN.R-project.org/web/views/, @CRAN{} Task Views}, allowing
to browse packages by topic and providing tools to automatically install
all packages for special areas of interest.

@c Some @CRAN{} packages that do not build out of the box on Windows,
@c require additional software, or are shipping third party libraries for
@c Windows cannot be made available on @CRAN{} in form of a Windows binary
@c packages.  Nevertheless, some of these packages are available at the
@c ``@CRAN{} extras'' repository at
@c @url{https://www.stats.ox.ac.uk/pub/RWin/} kindly provided by Brian
@c D. Ripley.  Note that this repository is a default repository for recent
@c versions of R for Windows.

@c @node Add-on packages from Omegahat
@c @subsection Add-on packages from Omegahat

@c The @url{http://www.omegahat.net/, Omega Project for Statistical
@c Computing} provides a variety of open-source software for statistical
@c applications, with special emphasis on web-based software, Java, the
@c Java virtual machine, and distributed computing.  A @acronym{CRAN} style
@c R package repository is available via @url{http://www.omegahat.net/R/}.
@c See @url{http://www.omegahat.net/} for information on most R packages
@c available from the Omega project.

@node Add-on packages from Bioconductor
@subsection Add-on packages from Bioconductor

@url{https://www.bioconductor.org/, Bioconductor} is an open source and
open development software project for the analysis and comprehension of
genomic data.  Most Bioconductor components are distributed as R add-on
packages.  Initially most of the
@url{https://bioconductor.org/packages/release/BiocViews.html#___Software,
Bioconductor software packages}
focused primarily on DNA microarray data analysis.  As the 
project has matured, the functional scope of the software packages
broadened to include the analysis of all types of genomic data, such as
SAGE, sequence, or SNP data.  In addition, there are metadata
(annotation, CDF and probe) and experiment data packages.  See
@url{https://bioconductor.org/install/} for available packages and a
complete taxonomy via @I{BioC Views}.

@node Other add-on packages
@subsection Other add-on packages

Many more packages are available from places other than the default
repositories discussed above (@CRAN{} and Bioconductor).  In particular,
R-Forge provides a @CRAN{} style repository at
@url{https://R-Forge.R-project.org/}.

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?
@section How can add-on packages be installed?

(Unix-like only.)  The add-on packages on @CRAN{} come as gzipped tar
files named @code{@var{pkg}_@var{version}.tar.gz}.  Let @var{path} be
the path to such a package file.  Provided that @command{tar} and
@command{gzip} are available on your system, type

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

@noindent
at the shell prompt to install to the library tree rooted at the first
directory in your library search path (see the help page for
@code{.libPaths()} for details on how the search path is determined).

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

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

@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 repositories such as
@CRAN{}.  See the help page for @code{available.packages()} for more
information.

@c <COMMENT>
@c This is really no longer quite accurate (R_LIBS_USER is preferred to
@c R_LIBS), and described in ?libPaths anyways ... hence comment out.
@c You can use several library trees of add-on packages.  The easiest way
@c to tell R to use these is via the environment variable @env{R_LIBS}
@c which should be a colon-separated list of directories at which R library
@c trees are rooted.  You do not have to specify the default tree in
@c @env{R_LIBS}.  E.g., to use a private tree in @file{$HOME/lib/R} and a
@c public site-wide tree in @file{/usr/local/lib/R-contrib}, put

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

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

@c @example
@c R_LIBS="~/lib/R:/usr/local/lib/R-contrib"
@c @end example

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

@node How can add-on packages be used?
@section How can add-on packages be used?

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

@example
library()
@end example

@noindent
at the R prompt.  

This produces something like

@quotation
@cartouche
@smallexample
Packages in library '/home/me/lib/R':

mystuff       My own R functions, nicely packaged but not documented

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

KernSmooth    Functions for Kernel Smoothing Supporting Wand & Jones (1995)
MASS          Support Functions and Datasets for Venables and Ripley's MASS
Matrix        Sparse and Dense Matrix Classes and Methods
base          The R Base Package
boot          Bootstrap Functions (Originally by Angelo Canty for S)
class         Functions for Classification
cluster       "Finding Groups in Data": Cluster Analysis Extended
              Rousseeuw et al.
codetools     Code Analysis Tools for R
compiler      The R Compiler Package
datasets      The R Datasets Package
foreign       Read Data Stored by 'Minitab', 'S', 'SAS', 'SPSS', 'Stata',
              'Systat', 'Weka', 'dBase', ...
grDevices     The R Graphics Devices and Support for Colours and Fonts
graphics      The R Graphics Package
grid          The Grid Graphics Package
lattice       Trellis Graphics for R
methods       Formal Methods and Classes
mgcv          Mixed GAM Computation Vehicle with Automatic Smoothness
              Estimation
nlme          Linear and Nonlinear Mixed Effects Models
nnet          Feed-Forward Neural Networks and Multinomial Log-Linear
              Models
parallel      Support for Parallel Computation in R
rpart         Recursive Partitioning and Regression Trees
spatial       Functions for Kriging and Point Pattern Analysis
splines       Regression Spline Functions and Classes
stats         The R Stats Package
stats4        Statistical Functions using S4 Classes
survival      Survival Analysis
tcltk         Tcl/Tk Interface
tools         Tools for Package Development
utils         The R Utils Package
@end smallexample
@end cartouche
@end quotation

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

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

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

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

You can remove the loaded package @var{pkg} from the @code{search()} path by

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

@noindent
(which does not by default unload the namespace, see @code{?detach}).

@node How can add-on packages be removed?
@section How can add-on packages be removed?

Use

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

@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.

@c (Versions of R prior to 1.3.0 removed from the default library by default.)

To remove from library @var{lib}, do

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

@node How can I create an R package?
@section How can I create an R package?

A package consists of a subdirectory containing a file
@file{DESCRIPTION} and the subdirectories @file{R}, @file{data},
@file{demo}, @file{exec}, @file{inst}, @file{man}, @file{po},
@file{src}, and @file{tests} (some of which can be missing).  The
package subdirectory may also contain files @file{INDEX},
@file{NAMESPACE}, @file{configure}, @file{cleanup}, @file{LICENSE},
@file{LICENCE}, @file{COPYING} and @file{NEWS}.

@xref{Creating R packages, , , R-exts, Writing R Extensions}
for details.  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?
@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.

The @url{https://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 SVN miscellanea.



@node R and Emacs
@chapter R and Emacs


@node Is there Emacs support for R?
@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 (R, S 3/4, and @SPLUS{}
3.x/4.x/5.x/6.x/7.x), @I{LispStat} dialects (@I{XLispStat}, @I{ViSta}),
SAS, @I{Stata}, and @I{BUGS}.

@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, @I{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 stable version of @acronym{ESS} is available via @CRAN{} or
the @url{https://ESS.R-project.org/, ESS web page}.

@acronym{ESS} comes with detailed installation instructions.

For help with @acronym{ESS}, send email to
@email{ESS-help@@r-project.org}.

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

@node Should I run R from within Emacs?
@section Should I run R from within Emacs?

Yes, instead of just running it in a console, @emph{definitely}.  As an
alternative to other @abbr{IDE}s such as @I{RStudio}, @emph{possibly}, notably if you
are interested to use Emacs for other computer interaction.
You'd be using @acronym{ESS}, Emacs Speaks Statistics, see previous FAQ.

Inferior R mode provides a @I{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
@section Debugging R from within Emacs

To debug R ``from within Emacs'', there are several possibilities.  To
use the Emacs @abbr{GUD} (Grand Unified Debugger) library with the recommended
debugger @I{GDB}, type @kbd{M-x gdb} and give the path to the R
@emph{binary} as argument.  At the @command{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 --quiet}).

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 @abbr{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 @I{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 @abbr{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:

@example
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 example



@node R Miscellanea
@chapter R Miscellanea


@c @node Why does R run out of memory?
@c @section Why does R run out of memory?

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

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

@c The new garbage collector does not move objects in memory, meaning that
@c it is possible for the free memory to become fragmented so that large
@c objects cannot be allocated even when there is apparently enough memory
@c for them.

@c @node Why does sourcing a correct file fail?
@c @section Why does sourcing a correct file fail?

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

@node How can I set components of a list to NULL?
@section How can I set components of a list to NULL?

You can use

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

@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?
@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?
@section How can I clean up my workspace?

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

@example
rm(list = ls(all.names = TRUE))
@end example

@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?
@section How can I get @code{eval()} and @code{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,

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

Although this behavior may initially seem to be rather strange, it 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

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

@noindent
or

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

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

@node Why do my matrices lose dimensions?
@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,

@example
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 example

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

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

@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

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

@node How does autoloading work?
@section How does autoloading work?

Autoloading is rarely used since packages became lazy-loaded.

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?
@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

@example
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 example

@noindent
we obtain:

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

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?
@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?
@section Why does plotting give a color allocation error?

This is about a problem rarely seen with modern X11 installations.

On an X11 device, plotting sometimes, 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.)

@c One application which is notorious for ``eating'' colors is Netscape.
@c If the problem occurs when Netscape is running, try (re)starting it with
@c either the @option{-no-install} (to use the default colormap) or the
@c @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?
@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?
@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

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

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

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

In any case, do not call @code{as.numeric()} or their likes directly for
the task at hand (as @code{as.numeric()} or @code{unclass()} give the
internal codes).

@node Are Trellis displays implemented in R?
@section Are Trellis displays implemented in R?

The recommended package @CRANpkg{lattice} (which is based on base
package @pkg{grid}) provides graphical functionality that is compatible
with most Trellis commands.

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 chosen for the R
equivalent.)

@node What are the enclosing and parent environments?
@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.  (In C this would be done with
static variables.)

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?
@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

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

@noindent
(note that it is @samp{==} and not @samp{=}).  Sometimes @code{bquote()}
gives a more compact form, e.g.,

@example
title(bquote(hat(a) = .(ahat)))
@end example

@noindent
where subexpressions enclosed in @samp{.()} are replaced by their
values.

There are more examples in the mailing list archives.

@node What are valid names?
@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 and
underscore characters, and starts with either a letter or a dot not
followed by a number.  Reserved words are not syntactic names.
@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?
@section Are GAM@w{s} implemented in R?

Package @CRANpkg{gam} from @CRAN{} implements all the Generalized
Additive Models (GAM) functionality as described in the GAM chapter of
the White Book.  In particular, it implements backfitting with both
local regression and smoothing splines, and is extendable.  There is a
@code{gam()} function for GAM@w{s} in package @CRANpkg{mgcv}, but it is not
an exact clone of what is described in the White Book (no @code{lo()}
for example).  Package @CRANpkg{gss} can fit spline-based GAM@w{s} too.  And
if you can accept regression splines you can use @code{glm()}.  For
Gaussian GAM@w{s} you can use @code{bruto()} from package @CRANpkg{mda}.

@node Why is the output not printed when I source() a file?
@section Why is the output not printed when I source() a file?

Most R commands do not generate any output. The command

@example
1+1
@end example

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

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

@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

@example
print(1+1)
@end example

@noindent
or

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

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

@node Why does outer() behave strangely with my function?
@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

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

@noindent
If you define the general function

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

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

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

Scalar functions can also be vectorized using @code{Vectorize()}.

@node Why does the output from anova() depend on the order of factors in the model?
@section Why does the output from @code{anova()} depend on the order of factors in the model?

In a model such as @code{~A+B+A:B}, R will report the difference in sums
of squares between the models @code{~1}, @code{~A}, @code{~A+B} and
@code{~A+B+A:B}.  If the model were @code{~B+A+A:B}, R would report
differences between @code{~1}, @code{~B}, @code{~A+B}, and
@code{~A+B+A:B} . In the first case the sum of squares for @code{A} is
comparing @code{~1} and @code{~A}, in the second case it is comparing
@code{~B} and @code{~B+A}.  In a non-orthogonal design (i.e., most
unbalanced designs) these comparisons are (conceptually and numerically)
different.

Some packages report instead the sums of squares based on comparing the
full model to the models with each factor removed one at a time (the
famous `Type III sums of squares' from SAS, for example).  These do not
depend on the order of factors in the model.  The question of which set
of sums of squares is the Right Thing provokes low-level holy wars on
R-help from time to time.

There is no need to be agitated about the particular sums of squares
that R reports.  You can compute your favorite sums of squares quite
easily.  Any two models can be compared with @code{anova(@var{model1},
@var{model2})}, and @code{drop1(@var{model1})} will show the sums of
squares resulting from dropping single terms.

@node How do I produce PNG graphics in batch mode?
@section How do I produce PNG graphics in batch mode?

Under a Unix-like, if your installation supports the
@code{type="cairo"} option to the @code{png()} device there should be no
problems, and the default settings should just work.  This option is not
available for versions of R prior to 2.7.0, or without support for
@I{cairo}.  From R 2.7.0 @code{png()} by default uses the Quartz device
on macOS, and that too works in batch mode.

Earlier versions of the @code{png()} device used the X11 driver, which
is a problem in batch mode or for remote operation.  If you have
Ghostscript you can use @code{bitmap()}, which produces a PostScript or
PDF file then converts it to any bitmap format supported by @I{Ghostscript}.
On some installations this produces ugly output, on others it is
perfectly satisfactory.  Many systems now come with @I{Xvfb} from
@url{https://www.x.org/, X.Org} (possibly as an optional
install), which is an X11 server that does not require a screen.

@c ; and there is the @CRANpkg{GDD} package from @CRAN{}, which produces
@c PNG, JPEG and GIF bitmaps without X11.

@node How can I get command line editing to work?
@section How can I get command line editing to work?

The Unix-like command-line interface to R can only provide the inbuilt
command line editor which allows recall, editing and re-submission of
prior commands provided that the @acronym{GNU} @I{readline} library is
available at the time R is configured for compilation.  Note that the
`development' version of @I{readline} including the appropriate headers is
needed: users of Linux binary distributions will need to install
packages such as @code{libreadline-dev} (Debian) or
@code{readline-devel} (Red Hat).

@node How can I turn a string into a variable?
@section How can I turn a string into a variable?

If you have

@example
varname <- c("a", "b", "d")
@end example

@noindent
you can do

@example
get(varname[1]) + 2
@end example

@noindent
for

@example
a + 2
@end example

@noindent
or

@example
assign(varname[1], 2 + 2)
@end example

@noindent
for

@example
a <- 2 + 2
@end example

@noindent
or

@example
eval(substitute(lm(y ~ x + variable),
                list(variable = as.name(varname[1]))))
@end example

@noindent
for

@example
lm(y ~ x + a)
@end example

At least in the first two cases it is often easier to just use a list,
and then you can easily index it by name

@example
vars <- list(a = 1:10, b = rnorm(100), d = LETTERS)
vars[["a"]]
@end example

@noindent
without any of this messing about.  This becomes especially true if you
are finding yourself creating and trying to programmatically access
groups of related variables such as @code{result1}, @code{result2},
@code{result3}, and so on: instead of fighting against the language to
use

@example
assign(paste0("result", i), process(get(paste0("dataset", i))))
@end example

@noindent
it is much easier to put the related variables in lists and use

@example
result[[i]] <- process(dataset[[i]])
@end example

@noindent
and, eventually,

@example
result <- lapply(dataset, process)
@end example

@noindent
which is easy to replace with @code{parLapply} for parallel processing.

@node Why do lattice/trellis graphics not work?
@section Why do lattice/trellis graphics not work?

The most likely reason is that you forgot to tell R to display the
graph.  Lattice functions such as @code{xyplot()} create a graph object,
but do not display it (the same is true of @CRANpkg{ggplot2} graphics,
and Trellis graphics in @SPLUS{}).  The @code{print()} method for the
graph object produces the actual display.  When you use these functions
interactively at the command line, the result is automatically printed,
but in @code{source()} or inside your own functions you will need an
explicit @code{print()} statement.

@node How can I sort the rows of a data frame?
@section How can I sort the rows of a data frame?

To sort the rows within a data frame, with respect to the values in one
or more of the columns, simply use @code{order()} (e.g.,
@code{DF[order(DF$a, DF[["b"]]), ]} to sort the data frame @code{DF} on
columns named @code{a} and @code{b}).

From R 4.4.0, @code{sort_by()} provides a less verbose alternative
with a formula interface (e.g., @code{sort_by(DF, ~a + b)}).

@node Why does the help.start() search engine not work?
@section Why does the help.start() search engine not work?

Since R 2.10.0, the browser-based search engine in @code{help.start()}
is an @HTML{} interface to @code{help.search()}, and should always work.
Before that, the engine utilized a Java applet.  In order for this to
function properly, one needed a compatible version of Java installed on
the system and linked to the browser, and both Java @emph{and}
JavaScript enabled in the browser.

@node Why did my .Rprofile stop working when I updated R?
@section Why did my @I{.Rprofile} stop working when I updated R?

Did you read the @file{NEWS} file?  For functions that are not in the
@pkg{base} package you need to specify the correct package namespace,
since the code will be run @emph{before} the packages are loaded.  E.g.,

@example
ps.options(horizontal = FALSE)
help.start()
@end example

@noindent
needs to be

@example
grDevices::ps.options(horizontal = FALSE)
utils::help.start()
@end example

@node Where have all the methods gone?
@section Where have all the methods gone?

Many functions, particularly S3 methods, are now hidden in namespaces.
This has the advantage that they cannot be called inadvertently with
arguments of the wrong class, but it makes them harder to view.

To see the code for an S3 method (e.g., @code{[.terms}) use

@example
getS3method("[", "terms")
@end example

@noindent
To see the code for an unexported function @code{foo()} in the namespace
of package @code{"bar"} use @code{bar:::foo}.  Don't use these
constructions to call unexported functions in your own code---they are
probably unexported for a reason and may change without warning.

@node How can I create rotated axis labels?
@section How can I create rotated axis labels?

To rotate axis labels (using base graphics), you need to use
@code{text()}, rather than @code{mtext()}, as the latter does not
support @code{par("srt")}.

@example
## @r{Increase bottom margin to make room for rotated labels}
par(mar = c(7, 4, 4, 2) + 0.1)
## @r{Create plot with no x axis and no x axis label}
plot(1 : 8, xaxt = "n",  xlab = "")
## @r{Set up x axis with tick marks alone}
axis(1, labels = FALSE)
## @r{Create some text labels}
labels <- paste("Label", 1:8, sep = " ")
## @r{Plot x axis labels at default tick marks}
text(1:8, par("usr")[3] - 0.25, srt = 45, adj = 1,
     labels = labels, xpd = TRUE)
## @r{Plot x axis label at line 6 (of 7)}
mtext(1, text = "X Axis Label", line = 6)
@end example

@noindent
When plotting the x axis labels, we use @code{srt = 45} for text
rotation angle, @code{adj = 1} to place the right end of text at the
tick marks, and @code{xpd = TRUE} to allow for text outside the plot
region.  You can adjust the value of the @code{0.25} offset as required
to move the axis labels up or down relative to the x axis.  See
@code{?par} for more information.

Also see Figure 1 and associated code in 
@I{Paul Murrell} (2003),
``Integrating grid Graphics Output with Base Graphics Output'',
@emph{R News}, @strong{3/2}, 7--12.

@node Why is read.table() so inefficient?
@section Why is read.table() so inefficient?

By default, @code{read.table()} needs to read in everything as character
data, and then try to figure out which variables to convert to numerics
or factors.  For a large data set, this takes considerable amounts of
time and memory.  Performance can substantially be improved by using the
@code{colClasses} argument to specify the classes to be assumed for the
columns of the table.

@node What is the difference between package and library?
@section What is the difference between package and library?

A @dfn{package} is a standardized collection of material extending R,
e.g.@: providing code, data, or documentation.  A @dfn{library} is a
place (directory) where R knows to find packages it can use (i.e., which
were @dfn{installed}).  R is told to use a package (to ``load'' it and
add it to the search path) via calls to the function @code{library}.
I.e., @code{library()} is employed to load a package from libraries
containing packages.

@xref{R Add-On Packages}, for more details.  See also @I{Uwe Ligges} (2003),
``R Help Desk: Package Management'', @emph{R News}, @strong{3/3},
37--39.

@node I installed a package but the functions are not there
@section I installed a package but the functions are not there

To actually @emph{use} the package, it needs to be @emph{loaded} using
@code{library()}.

See @ref{R Add-On Packages} and @ref{What is the difference between
package and library?} for more information.

@node Why doesn't R think these numbers are equal?
@section Why doesn't R think these numbers are equal?

The only numbers that can be represented exactly in R's numeric type are
integers and fractions whose denominator is a power of 2.  All other
numbers are internally rounded to (typically) 53 binary digits accuracy.
As a result, two floating point numbers will not reliably be equal
unless they have been computed by the same algorithm, and not always
even then.  For example

@example
R> a <- sqrt(2)
R> a * a == 2
[1] FALSE
R> a * a - 2
[1] 4.440892e-16
R> print(a * a, digits = 18)
[1] 2.00000000000000044
@end example

The function @code{all.equal()} compares two objects using a numeric
tolerance of @code{.Machine$double.eps ^ 0.5}.  If you want much greater
accuracy than this you will need to consider error propagation
carefully.

A discussion with many easily followed examples is in Appendix G
``Computational Precision and Floating Point Arithmetic'', pages
753--771 of @emph{Statistical Analysis and Data Display: An Intermediate
Course with Examples in R}, @I{Richard M. Heiberger} and @I{Burt Holland}
(@I{Springer} 2015, second edition).
This appendix is a free download from
@url{https://link.springer.com/content/pdf/bbm:978-1-4939-2122-5/1.pdf}.

For more information, see e.g.@: 
@I{David Goldberg} (1991), 
``What Every Computer Scientist Should Know About Floating-Point Arithmetic'',
@I{@emph{ACM Computing Surveys}}, @strong{23/1}, 5--48, 
also available via
@c As of 2020-09-25, redirects to https without valid certificate ...
@c @url{http://www.validlab.com/goldberg/paper.pdf}.
@c See <https://en.wikipedia.org/wiki/IEEE_754>:
@url{https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html}.

Here is another example, this time using addition:

@example
R> .3 + .6 == .9
[1] FALSE
R> .3 + .6 - .9
[1] -1.110223e-16
R> print(matrix(c(.3,  .6,  .9, .3 + .6)), digits = 18)
                     [,1]
[1,] 0.299999999999999989
[2,] 0.599999999999999978
[3,] 0.900000000000000022
[4,] 0.899999999999999911
@end example


@node How can I capture or ignore errors in a long simulation?
@section How can I capture or ignore errors in a long simulation?

Use @code{try()}, which returns an object of class @code{"try-error"}
instead of an error, or preferably @code{tryCatch()}, where the return
value can be configured more flexibly.  For example

@example
beta[i,] <- tryCatch(coef(lm(formula, data)),
                     error = function(e) rep(NaN, 4))
@end example

@noindent
would return the coefficients if the @code{lm()} call succeeded and
would return @code{c(NaN, NaN, NaN, NaN)} if it failed (presumably there
are supposed to be 4 coefficients in this example).

@node Why are powers of negative numbers wrong?
@section Why are powers of negative numbers wrong?

You are probably seeing something like

@example
R> -2^2
[1] -4
@end example

@noindent
and misunderstanding the precedence rules for expressions in R.
Write

@example
R> (-2)^2
[1] 4
@end example

@noindent
to get the square of @math{-2}.

The precedence rules are documented in @code{?Syntax}, and to see how R
interprets  an expression you can look at the parse tree

@example
R> as.list(quote(-2^2))
[[1]]
`-`

[[2]]
2^2
@end example

@node How can I save the result of each iteration in a loop into a separate file?
@section How can I save the result of each iteration in a loop into a separate file?

One way is to use @code{paste()} (or @code{sprintf()}) to concatenate a
stem filename and the iteration number while @code{file.path()}
constructs the path.  For example, to save results into files
@file{result1.rda}, @dots{}, @file{result100.rda} in the subdirectory
@file{Results} of the current working directory, one can use

@example
for(i in 1:100) @{
  ## Calculations constructing "some_object" ...
  fp <- file.path("Results", paste0("result", i, ".rda"))
  save(list = "some_object", file = fp)
@}
@end example

@node Why are p-values not displayed when using lmer()?
@section Why are @math{p}-values not displayed when using @code{lmer()}?

Doug Bates has kindly provided an extensive response in a post to the 
r-help list, which can be reviewed at
@uref{https://stat.ethz.ch/pipermail/r-help/2006-May/094765.html}.

@node Why are there unwanted borders
@section Why are there unwanted borders, lines or grid-like artifacts when viewing a plot saved to a PS or PDF file?

This can occur when using functions such as @code{polygon()},
@code{filled.contour()}, @code{image()} or other functions which may
call these internally.  In the case of @code{polygon()}, you may observe
unwanted borders between the polygons even when setting the
@code{border} argument to @code{NA} or @code{"transparent"}.

The source of the problem is the PS/PDF viewer when the plot is
anti-aliased.  The details for the solution will be different depending
upon the viewer used, the operating system and may change over time.
For some common viewers, consider the following:

@ftable @asis
@item Acrobat Reader (cross platform)
There are options in Preferences to enable/disable text smoothing, image
smoothing and line art smoothing.
Disable line art smoothing.
@item Preview (macOS)
There is an option in Preferences to enable/disable anti-aliasing of
text and line art.
Disable this option. 
@item @I{GSview} (cross platform)
There are settings for Text Alpha and Graphics Alpha.
Change Graphics Alpha from 4 bits to 1 bit to disable graphic
anti-aliasing.
@item @I{gv} (Unix-like X)
There is an option to enable/disable anti-aliasing.
Disable this option.
@item Evince (Linux/GNOME)
There is not an option to disable anti-aliasing in this viewer.
@item @I{Okular} (Linux/KDE)
There is not an option in the GUI to enable/disable anti-aliasing.
From a console command line, use:
@smallexample
$ kwriteconfig --file okularpartrc --group 'Dlg Performance' \
               --key GraphicsAntialias Disabled
@end smallexample
Then restart @I{Okular}.  Change the final word to @samp{Enabled} to restore
the original setting.
@end ftable

@node Why does backslash behave strangely inside strings?
@section Why does backslash behave strangely inside strings?

This question most often comes up in relation to file names (see
@ref{How do file names work in Windows?})  but it also happens that
people complain that they cannot seem to put a single @samp{\} character
into a text string unless it happens to be followed by certain other
characters.

To understand this, you have to distinguish between character strings
and @emph{representations} of character strings.  Mostly, the
representation in R is just the string with a single or double quote at
either end, but there are strings that cannot be represented that way,
e.g., strings that themselves contain the quote character.  So

@example
> str <- "This \"text\" is quoted"
> str
[1] "This \"text\" is quoted"
> cat(str, "\n")
This "text" is quoted
@end example

@noindent
The @emph{escape sequences} @samp{\"} and @samp{\n} represent a double
quote and the newline character respectively. Printing text strings,
using @code{print()} or by typing the name at the prompt will use the
escape sequences too, but the @code{cat()} function will display the
string as-is. Notice that @samp{"\n"} is a one-character string, not
two; the backslash is not actually in the string, it is just generated
in the printed representation.

@example
> nchar("\n")
[1] 1
> substring("\n", 1, 1)
[1] "\n"
@end example

So how do you put a backslash in a string? For this, you have to
escape the escape character. I.e., you have to double the backslash.
as in

@example
> cat("\\n", "\n")
\n
@end example

Some functions, particularly those involving regular expression
matching, themselves use metacharacters, which may need to be escaped by
the backslash mechanism.  In those cases you may need a @emph{quadruple}
backslash to represent a single literal one.

In versions of R up to 2.4.1 an unknown escape sequence like @samp{\p}
was quietly interpreted as just @samp{p}.  Current versions of R emit a
warning.

@node How can I put error bars or confidence bands on my plot?
@section How can I put error bars or confidence bands on my plot?

Some functions will display a particular kind of plot with error bars,
such as the @code{bar.err()} function in the @CRANpkg{agricolae}
package, the @code{plotCI()} function in the @CRANpkg{gplots} package,
the @code{plotCI()} and @code{brkdn.plot()} functions in the
@CRANpkg{plotrix} package and the @code{error.bars()},
@code{error.crosses()} and @code{error.bars.by()} functions in the
@CRANpkg{psych} package.  Within these types of functions, some will
accept the measures of dispersion (e.g., @code{plotCI}), some will
calculate the dispersion measures from the raw values (@code{bar.err},
@code{brkdn.plot}), and some will do both (@code{error.bars}).  Still
other functions will just display error bars, like the dispersion
function in the @CRANpkg{plotrix} package.  Most of the above functions
use the @code{arrows()} function in the base @pkg{graphics} package to
draw the error bars.

The above functions all use the base graphics system.  The grid and
lattice graphics systems also have specific functions for displaying
error bars, e.g., the @code{grid.arrow()} function in the @pkg{grid}
package, and the @code{geom_errorbar()}, @code{geom_errorbarh()},
@code{geom_pointrange()}, @code{geom_linerange()},
@code{geom_crossbar()} and @code{geom_ribbon()} functions in the
@CRANpkg{ggplot2} package.  In the lattice system, error bars can be
displayed with @code{Dotplot()} or @code{xYplot()} in the
@CRANpkg{Hmisc} package and @code{segplot()} in the
@CRANpkg{latticeExtra} package.

@node How do I create a plot with two y-axes?
@section How do I create a plot with two y-axes?

Creating a graph with two y-axes, i.e., with two sorts of data that are
scaled to the same vertical size and showing separate vertical axes on
the left and right sides of the plot that reflect the original scales of
the data, is possible in R but is not recommended.  The basic approach
for constructing such graphs is to use @code{par(new=TRUE)} (see
@code{?par}); functions @code{twoord.plot()} (in the @CRANpkg{plotrix}
package) and @code{doubleYScale()} (in the @CRANpkg{latticeExtra}
package) automate the process somewhat.
@c See
@c @url{http://rwiki.sciviews.org/doku.php?id=tips:graphics-base:2yaxes}
@c for more information, including strong arguments against this sort of
@c graph.

@node How do I access the source code for a function?
@section How do I access the source code for a function?

In most cases, typing the name of the function will print its source 
code. However, code is sometimes hidden in a namespace, or compiled.  For 
a complete overview on how to access source code, see @I{Uwe Ligges} (2006),
``Help Desk: Accessing the sources'', @emph{R News}, @strong{6/4},
43--45 (@url{https://CRAN.R-project.org/doc/Rnews/Rnews_2006-4.pdf}).

@node Why does summary() report strange results for the R^2 estimate when I fit a linear model with no intercept?
@section Why does summary() report strange results for the R^2 estimate when I fit a linear model with no intercept?

As described in @code{?summary.lm}, when the intercept is zero (e.g.,
from @code{y ~ x - 1} or @code{y ~ x + 0}), @code{summary.lm()} uses the
formula
@eqn{R^2 = 1 - \sum_i R_i^2 / \sum_i y_i^2,
     R^2 = 1 - Sum(R[i]^2) / Sum((y[i])^2)},
which is different from the usual
@eqn{R^2 = 1 - \sum R_i^2 / \sum_i (y_i - \hbox{mean}(y))^2,
     R^2 = 1 - Sum(R[i]^2) / Sum((y[i] - mean(y))^2)}.
There are several reasons for this:
@itemize
@item
Otherwise the @math{R^2} could be negative (because the model with zero
intercept can fit @emph{worse} than the constant-mean model it is
implicitly compared to).
@item
If you set the slope to zero in the model with a line through the
origin you get fitted values y*=0
@item
The model with constant, non-zero mean is not nested in the model
with a line through the origin.
@end itemize

All these come down to saying that if you know @emph{@I{a priori}} that
@math{E[Y]=0} when @math{x=0} then the `null' model that you should
compare to the fitted line, the model where @math{x} doesn't explain any
of the variance, is the model where @math{E[Y]=0} everywhere.  (If you
don't know @I{a priori} that @math{E[Y]=0} when @math{x=0}, then you
probably shouldn't be fitting a line through the origin.)

@node Why is R apparently not releasing memory?
@section Why is R apparently not releasing memory?

This question is often asked in different flavors along the lines of
``I have removed objects in R and run @code{gc()} and yet
@code{ps}/@code{top} still shows the R process using a lot of
memory'', often on Linux machines.

This is an artifact of the way the operating system (OS) allocates
memory.  In general it is common that the OS is not capable of
releasing all unused memory.  In extreme cases it is possible that even
if R frees almost all its memory, the OS can not release any of it due
to its design and thus tools such as @code{ps} or @code{top} will
report substantial amount of resident RAM used by the R process even
though R has released all that memory.  In general such tools do
@emph{not} report the actual memory usage of the process but rather
what the OS is reserving for that process.

The short answer is that this is a limitation of the memory allocator
in the operating system and there is nothing R can do about it. That
space is simply kept by the OS in the hope that R will ask for it
later.  The following paragraph gives more in-depth answer with
technical details on how this happens.

Most systems use two separate ways to allocate memory. For allocation
of large chunks they will use @code{mmap} to map memory into the
process address space.  Such chunks can be released immediately when
they are completely free, because they can reside anywhere in the
virtual memory.  However, this is a relatively expensive operation and
many OSes have a limit on the number of such allocated chunks, so this
is only used for allocating large memory regions.  For smaller
allocations the system can expand the data segment of the process
(historically using the @code{brk} system call), but this whole area
is always contiguous.  The OS can only move the end of this space, it
cannot create any ``holes''. Since this operation is fairly cheap, it
is used for allocations of small pieces of memory.  However, the
side-effect is that even if there is just one byte that is in use
at the end of the data segment, the OS cannot release any memory
at all, because it cannot change the address of that byte.  This is
actually more common than it may seem, because allocating a lot of
intermediate objects, then allocating a result object and removing all
intermediate objects is a very common practice.  Since the result is
allocated at the end it will prevent the OS from releasing any memory
used by the intermediate objects.  In practice, this is not necessarily
a problem, because modern operating systems can page out unused
portions of the virtual memory so it does not necessarily reduce the
amount of real memory available for other applications.  Typically,
small objects such as strings or pairlists will be affected by this
behavior, whereas large objects such as long vectors will be allocated
using @code{mmap} and thus not affected.  On Linux (and possibly other
Unix-like systems) it is possible to use the @code{mallinfo} system call
(also see the @url{https://rforge.net/mallinfo, mallinfo} package) to
query the allocator about the layout of the allocations, including the
actually used memory as well as unused memory that cannot be released.

@node How can I enable secure https downloads in R?
@section How can I enable secure @I{https} downloads in R?

From R 4.2.0, @code{"libcurl"} download method is always available and
used for @abbr{HTTPS} by default on all platforms.  It has been used
since R 3.3.0 everywhere but Windows where the default method
@code{"wininet"} also supported @abbr{HTTPS}.

So nothing needs to be done to access @samp{https://} websites in recent
versions of R.

@node How can I get CRAN package binaries for outdated versions of R?
@section How can I get CRAN package binaries for outdated versions of R?

Since March 2016, Windows and macOS binaries of @CRAN{} packages for old
versions of R (released more than 5 years ago) are made available from a
central @CRAN{} archive server instead of the @CRAN{} mirrors.  To get
these, one should set the @CRAN{} ``mirror'' element of the @code{repos}
option accordingly, by something like
@example
local(@{r <- getOption("repos")
       r["CRAN"] <- "http://CRAN-archive.R-project.org"
       options(repos = r)
      @})
@end example
@noindent
(see @code{?options} for more information).



@node R Programming
@chapter R Programming


@node How should I write summary methods?
@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?
@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.

@xref{Finding entry points, , Finding entry points in dynamically loaded
code, R-exts, Writing R Extensions}.  This manual is included in the R
distribution, @pxref{What documentation exists for R?}.

@node How can I inspect R objects when debugging?
@section How can I inspect R objects when debugging?

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

@xref{Inspecting R objects, , Inspecting R objects when debugging,
R-exts, Writing R Extensions}.

@node How can I change compilation flags?
@section How can I change compilation flags?

Suppose you have C code file for @I{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).

Starting with R 2.1.0, users can provide personal @file{Makevars} configuration
files in @file{$@env{HOME}/.R} to override the default flags.
@xref{Add-on packages, , , R-admin, R Installation and Administration}.

@node How can I debug S4 methods?
@section How can I debug S4 methods?

Use the @code{trace()} function with argument @code{signature=} to add
calls to the browser or any other code to the method that will be
dispatched for the corresponding signature.  See @code{?trace} for
details.



@node R Bugs
@chapter R Bugs


@node What is a bug?
@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.  For example, people sometimes
think there is a bug in R's mathematics because they don't understand
how finite-precision arithmetic works.  Rather than jumping to
conclusions, show the problem to someone who knows for certain.
Unexpected results of comparison of decimal numbers, for example
@code{0.28 * 100 != 28} or @code{0.1 + 0.2 != 0.3}, are not a bug.
@xref{Why doesn't R think these numbers are equal?}, for more details.

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.

See also ``Making sure it's a bug'' in
@uref{https://www.r-project.org/bugs.html, Bug Reporting in R} for more
information.

@node How to report a bug
@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

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

@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
(e.g., @url{https://en.wikipedia.org/wiki/Reproducibility}) 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.

Before you actually submit a bug report, you should check whether the
bug has already been reported and/or fixed.  First, try the ``Show open
bugs new-to-old'' or the search facility on
@url{https://bugs.R-project.org/}.  Second, consult
@url{https://svn.R-project.org/R/trunk/doc/NEWS.Rd}, which
records changes that will appear in the @emph{next} release of R,
including bug fixes that do not appear on the Bug Tracker.  
Third, if possible try the current r-patched or r-devel version of R.
If a bug has already been reported or fixed, please do not submit
further bug reports on it.  Finally, check carefully whether the bug is
with R, or a contributed package.  Bug reports on contributed packages
should be sent first to the package maintainer, and only submitted to
the R-bugs repository by package maintainers, mentioning the package in
the subject line.

A bug report can be generated using the function @code{bug.report()}.
For reports on R this will open the R Bugzilla page at
@url{https://bugs.R-project.org/}: for a contributed package it will open
the package's bug tracker Web page or help you compose an email to the
maintainer.  Since 2016, only ``members'' (including all who have
previously submitted bugs) can submit new bugs on the R Bugzilla.  See
``Where to submit bug reports and patches'' on 
@uref{https://www.r-project.org/bugs.html, Bug Reporting in R} for more
information.

There is a section of the bug repository for suggestions for
enhancements for R labelled @samp{wishlist}.  Suggestions can be
submitted in the same ways as bugs, but please ensure that the subject
line makes clear that this is for the wishlist and not a bug report, for
example by starting with @samp{Wishlist:}.

Comments on and suggestions for the Windows port of R should be sent to
@email{R-windows@@R-project.org}.

Corrections to and comments on message translations should be sent to the
last translator (listed at the top of the appropriate @samp{.po} file)
or to the translation team as listed at
@url{https://developer.R-project.org/TranslationTeams.html}.



@node Acknowledgments
@unnumbered 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 
@I{Doug Bates}, 
@I{Peter Dalgaard}, 
@I{Paul Gilbert},
@I{Stefano Iacus},
@I{Fritz Leisch},
@I{Jim Lindsey},
@I{Thomas Lumley},
@I{Martin Maechler},
@I{Brian D. Ripley},
@I{Anthony Rossini}, and 
@I{Andreas Weingessel}
for their comments which helped me improve this @acronym{FAQ}.

@c FIXME:
More to come soon @dots{}


@bye

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