\input texinfo
@c %**start of header
@setfilename R-exts.info
@settitle Writing R Extensions
@setchapternewpage on
@c %**end of header

@syncodeindex fn vr

@dircategory Programming
@direntry
* R Extensions: (R-exts).      Writing R Extensions.
@end direntry

@finalout

@include R-defs.texi
@include version.texi

@ifinfo
This is a guide to extending R.

@Rcopyright{1999}

@ignore
Permission is granted to process this file through TeX and print the
results, provided the printed document carries a copying permission
notice identical to this one except for the removal of this paragraph
(this paragraph not being relevant to the printed manual).

@end ignore

@permission{}
@c ---------- ^- read that
@end ifinfo

@titlepage
@title Writing R Extensions
@subtitle Version @value{VERSION}
@author R Development Core Team
@page
@vskip 0pt plus 1filll
@permission{}

@Rcopyright{1999}

@value{ISBN-exts}
@end titlepage

@ifnothtml
@contents
@end ifnothtml

@ifnottex
@node Top, Acknowledgements, (dir), (dir)
@top Writing R Extensions

This is a guide to extending R, describing the process of creating R
add-on packages, writing R documentation, R's system and foreign
language interfaces, and the R @acronym{API}.

The current version of this document is @value{VERSION}.

@value{ISBN-exts}
@end ifnottex

@menu
* Acknowledgements::
* Creating R packages::
* Writing R help files::
* Tidying and profiling R code::
* System and foreign language interfaces::
* The R API::
* Generic functions and methods::
* R (internal) programming miscellanea::
* R coding standards::
* Function and variable index::
* Concept index::
@end menu

@node Acknowledgements, Creating R packages, Top, Top
@unnumbered Acknowledgements


The contributions of Saikat DebRoy (who wrote the first draft of a guide
to using @code{.Call} and @code{.External}) and of Adrian Trapletti (who
provided information on the C++ interface) are gratefully acknowledged.

@node Creating R packages, Writing R help files, Acknowledgements, Top
@chapter Creating R packages
@cindex Packages
@cindex Creating packages

Packages provide a mechanism for loading optional code and attached
documentation as needed.  The @R{} distribution provides several
packages, such as @pkg{eda}, @pkg{mva}, and @pkg{stepfun}.

In the following, we assume that you know the @samp{library()} command,
including its @samp{lib.loc} argument, and we also assume basic
knowledge of @code{R CMD INSTALL}.  Otherwise, please look at @R{}'s
help pages

@smallexample
?library
?INSTALL
@end smallexample

@noindent
before reading on.  If the package you are writing uses the
@pkg{methods} package, look at the corresponding section in
@code{?INSTALL}.

@menu
* Package structure::
* Configure and cleanup::
* Checking and building packages::
* Writing package vignettes::
* Submitting a package to CRAN::
* Package name spaces::
@end menu

@node Package structure, Configure and cleanup, Creating R packages, Creating R packages
@section Package structure
@cindex Package structure

A package consists of a subdirectory containing the files
@file{DESCRIPTION} and optionally @file{INDEX}, and the subdirectories
@file{R}, @file{data}, @file{demo}, @file{exec}, @file{inst},
@file{man}, @file{src}, and @file{tests} (some of which can be missing).

Optionally the package can also contain (Bourne shell) script files
@file{configure} and @file{cleanup} which are executed before and
(provided that option @option{--clean} was given) after installation on
Unix, see @ref{Configure and cleanup}.

@menu
* The DESCRIPTION file::
* The INDEX file::
* Package subdirectories::
* Package bundles::
@end menu

@node The DESCRIPTION file, The INDEX file, Package structure, Package structure
@subsection The @file{DESCRIPTION} file
@cindex DESCRIPTION file

The @file{DESCRIPTION} file contains basic information about the package
in the following format:

@quotation
@cartouche
@smallexample
Package: pkgname
Version: 0.5-1
Date: 2000-01-04
Title: My first collection of functions
Author: Friedrich Leisch <F.Leisch@@ci.tuwien.ac.at>, with
  contributions from A. User <A.User@@whereever.net>.
Maintainer: Friedrich Leisch <F.Leisch@@ci.tuwien.ac.at>
Depends: R (>= 0.99), nlme
Description: A short (one paragraph) description of what
  the package does and why it may be useful.
License: GPL version 2 or newer
URL: http://www.r-project.org, http://www.another.url
@end smallexample
@end cartouche
@end quotation

@noindent
Continuation lines (for example, for descriptions longer than one line)
start with a space or tab.  The @samp{Package}, @samp{Version},
@samp{License}, @samp{Description}, @samp{Title}, @samp{Author}, and
@samp{Maintainer} fields are mandatory, the remaining fields
(@samp{Date}, @samp{Depends}, @samp{URL}, @dots{}) are optional.

The @samp{Package} and @samp{Version} fields give the name and the
version of the package, respectively.  The name should consist of
letters, numbers, and the dot character and start with a letter.  The
version is a sequence of at least @emph{two} non-negative integers
separated by single @samp{.} or @samp{-} characters.

The @samp{License} field should contain an explicit statement or a
well-known abbreviation (such as @samp{GPL}, @samp{LGPL}, @samp{BSD}, or
@samp{Artistic}), perhaps followed by a reference to the actual license
file.  It is very important that you include this information!
Otherwise, it may not even be legally correct for others to distribute
copies of the package.

The @samp{Description} field should give a comprehensive description of
what the package does.  One can use several (complete) sentences, but
only one paragraph.

The @samp{Title} field should give a short description of the package
and not have any continuation lines.  Older versions of @R{} used a
separate file @file{TITLE} for giving this information; this is now
deprecated in favor of using the @samp{Title} field in file
@file{DESCRIPTION} file.

The @samp{Author} field describes who wrote the package.  It is a plain
text field intended for human readers, but not for automatic processing
(such as extracting the email addresses of all listed contributors).

The @samp{Maintainer} field should give a @emph{single} name with email
address in angle brackets (for sending bug reports etc.).  It should not
end in a period or comma.

The optional @samp{Date} field gives the release date of the current
version of the package.  It is strongly recommended to use the yyyy-mm-dd
format conforming to the ISO standard.

The optional @samp{Depends} field gives a comma-separated list of
package names which this package depends on.  The package name may be
optionally followed by a comparison operator (currently only @samp{>=}
and @samp{<=} are supported), whitespace and a valid version number in
parentheses.  (List package names even if they are part of a bundle.)
You can also use the special package name @samp{R} if your package
depends on a certain version of R.  E.g., if the package works only with
R version 0.90 or newer, include @samp{R (>= 0.90)} in the
@samp{Depends} field.  Future versions of R will use this field to
autoload required packages, hence it is an error to use improper syntax
or misuse the @samp{Depends} field for comments on other software that
might be needed.  Other dependencies (external to the @R{} system)
should be listed in the @samp{SystemRequirements} field or a separate
@samp{README} file.  The @R{} @command{INSTALL} facilities already check
if the version of R used is recent enough for the package being
installed.

The optional @samp{URL} field may give a list of @acronym{URL}s
separated by commas or whitespace, for example the homepage of the
author or a page where additional material describing the software can
be found.  These @acronym{URL}s are converted to active hyperlinks on
@acronym{CRAN}.

@node The INDEX file, Package subdirectories, The DESCRIPTION file, Package structure
@subsection The @file{INDEX} file

The optional file @file{INDEX} contains a line for each sufficiently
interesting object in the package, giving its name and a description
(functions such as print methods not usually called explicitly might not
be included).  If the file is missing, the corresponding information is
automatically generated from the documentation sources (using
@code{Rdindex()} from package @pkg{tools}) when installing from source
and when using the package builder (@pxref{Checking and building
packages}).

@node Package subdirectories, Package bundles, The INDEX file, Package structure
@subsection Package subdirectories
@cindex Package subdirectories

The @file{R} subdirectory contains @R{} code files.  The code files to
be installed must start with a (lower or upper case) letter and have one
of the extensions @file{.R}, @file{.S}, @file{.q}, @file{.r}, or
@file{.s}.  We recommend using @file{.R}, as this extension seems to be
not used by any other software.  It should be possible to read in the
files using @code{source()}, so R objects must be created by
assignments.  Note that there need be no connection between the name of
the file and the R objects created by it.  If necessary, one of these
files (historically @file{zzz.R}) should use @code{library.dynam()}
@emph{inside} @code{.First.lib()} to load compiled code.

The @file{man} subdirectory should contain documentation files for the
objects in the package in @dfn{R documentation} (Rd) format.  The
documentation files to be installed must also start with a (lower or
upper case) letter and have the extension @file{.Rd} (the default) or
@file{.rd}.  @xref{Writing R help files}, for more information.  Note
that all user-level objects in a package should be documented; if a
package @var{pkg} contains user-level objects which are for ``internal''
use only, it should provide a file @file{@var{pkg}-internal.Rd} which
documents all such objects, and clearly states that these are not meant
to be called by the user.  See e.g.@: the sources for package
@pkg{tools} in the @R{} distribution for an example.

The @file{R} and @file{man} subdirectories may contain OS-specific
subdirectories named @file{unix}, @file{windows} or @file{mac}.

The C, C++, or FORTRAN@footnote{Note that Ratfor is not supported.  If
you have Ratfor source code, you need to convert it to FORTRAN.  On many
Solaris systems mixing Ratfor and FORTRAN code will work.} source files
for the compiled code are in @file{src}, plus optionally file
@file{Makevars} or @file{Makefile}.  When a package is installed using
@code{R CMD INSTALL}, Make is used to control compilation and linking
into a shared library for loading into @R{}.  There are default
variables and rules for this (determined when @R{} is configured and
recorded in @file{@var{R_HOME}/etc/Makeconf}).  These rules can be
tweaked by setting macros in a file @file{src/Makevars} (@pxref{Using
Makevars}).  Note that this mechanism should be general enough to
eliminate the need for a package-specific @file{Makefile}.  If such a
file is to be distributed, considerable care is needed to make it
general enough to work on all @R{} platforms.  In addition, it should
have a target @samp{clean} which removes all files generated by Make.
If necessary, platform-specific files can be used, for example
@file{Makevars.win} or @file{Makefile.win} on Windows take precedence
over @file{Makevars} or @file{Makefile}.

The @file{data} subdirectory is for additional data files the package
makes available for loading using @code{data()}.  Currently, data files
can have one of three types as indicated by their extension: plain R
code (@file{.R} or @file{.r}), tables (@file{.tab}, @file{.txt}, or
@file{.csv}), or @code{save()} images (@file{.RData} or @file{.rda}).
(As from @R{} 1.5.0 one can assume that all ports of @R{} have the same
binary (XDR) format and can read compressed images.  For portability to
earlier versions use images saved with @code{save(, ascii = TRUE,
version = 1)}.)  Note that R code should be ``self-sufficient'' and not
make use of extra functionality provided by the package, so that the
data file can also be used without having to load the package.  It is no
longer necessary to provide a @file{00Index} file in the @file{data}
directory---the corresponding information is generated automatically
from the documentation sources when installing from source, or when
using the package builder (@pxref{Checking and building packages}).

The @file{demo} subdirectory is for @R{} scripts (for running via
@code{demo()}) which demonstrate some of the functionality of the
package.  The script files must start with a (lower or upper case)
letter and have one of the extensions @file{.R} or @file{.r}.  If
present, the @file{demo} subdirectory should also have a @file{00Index}
file with one line for each demo, giving its name and a description.
(Note that it is not possible to generate this index file
automatically.)

The contents of the @file{inst} subdirectory will be copied recursively
to the installation directory.  Subdirectories of @file{inst} should not
interfere with those used by R (currently, @file{R}, @file{data},
@file{demo}, @file{exec}, @file{man}, @file{help}, @file{html},
@file{latex}, and @file{R-ex}).

Subdirectory @file{tests} is for additional package-specific test code,
similar to the specific tests that come with the @R{} distribution.
Test code can either be provided directly in a @file{.R} file, or via a
@file{.Rin} file containing code which in turn creates the corresponding
@file{.R} file (e.g., by collecting all function objects in the package
and then calling them with the strangest arguments).  The results of
running a @file{.R} file are written to a @file{.Rout} file.  If there
is a corresponding @file{.Rout.save} file, these two are compared, with
differences being reported but not causing an error.

Finally, @file{exec} could contain additional executables the package
needs, typically scripts for interpreters such as the shell, Perl, or
Tcl.  This mechanism is currently used only by a very few packages, and
still experimental.

@node  Package bundles,  , Package subdirectories, Package structure
@subsection Package bundles
@cindex Package bundles

Sometimes it is convenient to distribute several packages as a
@emph{bundle}.  (The main current example is @pkg{VR} which contains
four packages.)  The installation procedures on both Unix and Windows
can handle package bundles.

The @file{DESCRIPTION} file of a bundle has an extra @samp{Bundle}
field, as in

@quotation
@cartouche
@smallexample
Bundle: VR
Contains: MASS class nnet spatial
Version: 6.1-6
Date: 1999/11/26
Author: S original by Venables & Ripley.
  R port by Brian Ripley <ripley@@stats.ox.ac.uk>, following
  earlier work by Kurt Hornik and Albrecht Gebhardt.
BundleDescription: Various functions from the libraries of
  Venables and Ripley, `Modern Applied Statistics with S-PLUS'
  (3rd edition).
License: GPL (version 2 or later)
@end smallexample
@end cartouche
@end quotation

The @samp{Contains} field lists the packages, which should be contained
in separate subdirectories with the names given.  These are standard
packages in all respects except that the @file{DESCRIPTION} file is
replaced by a @file{DESCRIPTION.in} file which just contains fields
additional to the @file{DESCRIPTION} file of the bundle, for example

@quotation
@cartouche
@smallexample
Package: spatial
Description: Functions for kriging and point pattern analysis.
@end smallexample
@end cartouche
@end quotation

@node Configure and cleanup, Checking and building packages, Package structure, Creating R packages
@section Configure and cleanup

Note that most of this section is Unix-specific: see the comments
later on about the Windows and classic MacOS ports of R.

If your package needs some system-dependent configuration before
installation you can include a (Bourne shell) script @file{configure} in
your package which (if present) is executed by @code{R CMD INSTALL}
before any other action is performed.  This can be a script created by
the Autoconf mechanism, but may also be a script written by yourself.
Use this to detect if any nonstandard libraries are present such that
corresponding code in the package can be disabled at install time rather
than giving error messages when the package is compiled or used.  To
summarize, the full power of Autoconf is available for your extension
package (including variable substitution, searching for libraries,
etc.).

The (Bourne shell) script @file{cleanup} is executed as last thing by
@code{R CMD INSTALL} if present and option @option{--clean} was given,
and by @code{R CMD build} when preparing the package for building from
its source.  It can be used to clean up the package source tree.  In
particular, it should remove all files created by @command{configure}.

As an example consider we want to use functionality provided by a (C or
FORTRAN) library @code{foo}.  Using @command{autoconf}, we can create a
configure script which checks for the library, sets variable
@code{HAVE_FOO} to @code{TRUE} if it was found and with @code{FALSE}
otherwise, and then substitutes this value into output files (by
replacing instances of @samp{@@HAVE_FOO@@} in input files with the value
of @code{HAVE_FOO}).  For example, if a function named @code{bar} is to
be made available by linking against library @code{foo} (i.e., using
@option{-lfoo}), one could use

@smallexample
@group
AC_CHECK_LIB(foo, @var{fun}, [HAVE_FOO=TRUE], [HAVE_FOO=FALSE])
AC_SUBST(HAVE_FOO)
......
AC_CONFIG_FILES([foo.R])
AC_OUTPUT
@end group
@end smallexample

@noindent
in @file{configure.ac} (assuming Autoconf 2.50 or better).

The definition of the respective R function in @file{foo.R.in} could be

@smallexample
@group
foo <- function(x) @{
    if(!@@HAVE_FOO@@) stop("Sorry, library `foo' is not available")
    ...
@end group
@end smallexample

@noindent
From this file @command{configure} creates the actual R source file
@file{foo.R} looking like

@smallexample
@group
foo <- function(x) @{
    if(!FALSE) stop("Sorry, library `foo' is not available")
    ...
@end group
@end smallexample

@noindent
if library @code{foo} was not found (with the desired functionality).
In this case, the above @R{} code effectively disables the function.

One could also use different file fragments for available and missing
functionality, respectively.

You will very likely need to ensure that the same C compiler and
compiler flags are used in the @file{configure} tests as when compiling
@R{} or your package.  Under Unix, you can achieve this by including the
following fragment early in @file{configure.ac}

@smallexample
@group
: $@{R_HOME=`R RHOME`@}
if test -z "$@{R_HOME@}"; then
  echo "could not determine R_HOME"
  exit 1
fi
CC=`$@{R_HOME@}/bin/R CMD config CC`
CFLAGS=`$@{R_HOME@}/bin/R CMD config CFLAGS`
@end group
@end smallexample

@noindent
(using @samp{$@{R_HOME@}/bin/R} rather than just @samp{R} is necessary
in order to use the `right' version of @R{} when running the script as
part of @code{R CMD INSTALL}.)

@findex R CMD config
Note that earlier versions of this document recommended obtaining the
configure information by direct extraction (using grep and sed) from
@file{@var{R_HOME}/etc/Makeconf}, which only works for variables
recorded there as literals.  R 1.5.0 has added @code{R CMD config} for
getting the value of the basic configuration variables, or the header
and library flags necessary for linking against @R{}, see @kbd{R CMD
config --help} for more information.

If @R{} was configured to use the FORTRAN-to-C converter (f2c),
configure variable @code{F77} is set to a shell script wrapper to
compile/link FORTRAN 77 code based on f2c which for the purpose of
Autoconf qualifies as a FORTRAN 77 compiler.  E.g., to check for an
external BLAS library using the @code{ACX_BLAS} macro from the Official
Autoconf Macro Archive, one can simply do

@smallexample
@group
F77=`$@{R_HOME@}/bin/R CMD config F77`
AC_PROG_F77
FLIBS=`$@{R_HOME@}/bin/R CMD config FLIBS`
ACX_BLAS([], AC_MSG_ERROR([could not find your BLAS library], 1))
@end group
@end smallexample

Note that @code{FLIBS} as determined by R must be used to ensure that
FORTRAN 77 code works on all R platforms.  Calls to the Autoconf macro
@code{AC_F77_LIBRARY_LDFLAGS}, which would overwrite @code{FLIBS}, must
not be used (and hence e.g.@: removed from @code{ACX_BLAS}).  (Recent
versions of Autoconf in fact allow an already set @code{FLIBS} to
override the test for the Fortran linker flags.)

You should bear in mind that the configure script may well not work on
Windows systems (this seems normally to be the case for those generated
by Autoconf, although simple shell scripts do work).  If your package is
to be made publicly available, please give enough information for a user
on a non-Unix platform to configure it manually, or provide a
@file{configure.win} script to be used on that platform.

It is essential to provide manual configuration information if the
package is to be usable on classic MacOS.

In some rare circumstances, the configuration and cleanup scripts need
to know the location into which the package is being installed.  An
example of this is a package that uses C code and creates two shared
libraries/DLLs.  Usually, the library that is dynamically loaded by @R{}
is linked against the second, dependent, library.  On some systems, we
can add the location of this dependent library to the library that is
dynamically loaded by @R{}.  This means that each user does not have to
set the value of the @env{LD_LIBRARY_PATH} (or equivalent) environment
variable, but that the secondary library is automatically resolved.
Another example is when a package installs support files that are
required at run time, and their location is substituted into an @R{}
data structure at installation time. (This happens with the Java Archive
files in the @pkg{SJava} package.)

@vindex R_LIBRARY_DIR
@vindex R_PACKAGE_DIR
The names of the top-level library directory (i.e., specifiable via the
@samp{-l} argument) and the directory of the package itself are made
available to the installation scripts via the two shell/environment
variables @env{R_LIBRARY_DIR} and @env{R_PACKAGE_DIR}.  Additionally,
the name of the package (e.g., @samp{survival} or @samp{MASS}) being
installed is available from the shell variable @env{R_PACKAGE_NAME}.


@menu
* Using Makevars::
@end menu

@node Using Makevars,  , Configure and cleanup, Configure and cleanup
@subsection Using @file{Makevars}

Sometimes writing your own @file{configure} script can be avoided by
supplying a file @file{Makevars}: also one of the commonest uses of a
@file{configure} script is to make @file{Makevars} from
@file{Makevars.in}.

The most common use of a @file{Makevars} file is to set additional
compiler flags (for example include paths) by setting @code{PKG_CFLAGS},
@code{PKG_CXXFLAGS} and @code{PKG_FFLAGS}, for C, C++, or FORTRAN
respectively (@pxref{Creating shared libraries}).

Also, @file{Makevars} can be used to set flags for the linker, for
example @samp{-L} and @samp{-l} options.

There are some macros which are built whilst configuring the building of
@R{} itself, are stored in @file{@var{R_HOME}/etc/Makeconf} and can be
used in @file{Makevars}.  These include

@table @code
@item FLIBS
@vindex FLIBS
A macro containing the set of libraries need to link FORTRAN code.  This
may need to be included in @code{PKG_LIBS}.

@item BLAS_LIBS
@vindex BLAS_LIBS
A macro containing the BLAS libraries used when building @R{}.  This
may need to be included in @code{PKG_LIBS}.  Beware that if it is
empty then the @R{} executable will contain all the double-precision
BLAS routines, but no single-precision, complex nor double-complex
routines.

@item LAPACK_LIBS
@vindex LAPACK_LIBS
A macro containing the LAPACK libraries (and paths where appropriate)
used when building @R{}.  This may need to be included in
@code{PKG_LIBS}.  This may point to a shared library @code{libRlapack}
which contains all the double-precision LAPACK routines as well as those
double-complex LAPACK and BLAS routines needed to build @R{}, or it
may point to an external LAPACK library, or may be empty if an external
BLAS library also contains LAPACK.

[There is currently no guarantee that the LAPACK library will provide
more than the double-precision and double-complex driver routines used
by @R{}, and some do not provide all the auxiliary routines.]

The macro @code{BLAS_LIBS} should always be included @emph{after}
@code{LAPACK_LIBS}.
@end table



@node Checking and building packages, Writing package vignettes, Configure and cleanup, Creating R packages
@section Checking and building packages
@cindex Building packages
@cindex Checking packages

@findex R CMD check
Using @code{R CMD check}, the @R{} package checker, one can test whether
@emph{source} @R{} packages work correctly.  (Under Windows the
equivalent command is @code{Rcmd check}.)  This runs a series of checks.

@enumerate
@item
The package is installed.  This will warn about missing cross-references
and duplicate aliases in help files.

@item
The files and directories are checked for sufficient permissions (Unix
only).

@item
The @file{DESCRIPTION} file is checked for completeness, and some of its
entries for correctness.  Unless installation tests are skipped,
checking is aborted if the package dependencies cannot be resolved at
run time.

@item
Available index information (in particular, for demos and vignettes) is
checked for completeness.

@item
The R files are checked for syntax errors.

@item
The R files are checked for correct calls to @code{library.dynam} (with
no extension).  In addition, it is checked whether methods have all
arguments of the corresponding generic, and whether the final argument
of assignment functions is called @samp{value}.

@item
The Rd files are checked for the mandatory (@code{\name}, @code{\alias},
@code{\title}, @code{\description} and @code{\keyword}) fields, and for
unbalanced braces (which indicate Rd syntax errors).  The Rd name and
title are checked for being non-empty, and the keywords found are
compared to the standard ones.

@item
A check is made for undocumented user-level objects in the package.

@item
The functions and their documentation are compared, and any differences
in the call sequences reported.

@item
It is checked whether all function arguments given in @code{\usage}
sections of Rd files are documented in the corresponding
@code{\arguments} section.

@item
C source and header files are tested for correct (LF-only) line
endings.

@item
The examples provided by the package's documentation are run.
(@pxref{Writing R help files}, for information on using
@code{\examples} to create executable example code.)

Of course, released packages should be able to run at least their own
examples.

@item
If the package sources contain a @file{tests} directory then the tests
specified in that directory are run.  (Typically they will consist of a
set of @file{.R} source files and target output files
@file{.Rout.save}.)

@item
The code in package vignettes (@pxref{Writing package vignettes}) is
executed.

@item
If a working @command{latex} program is available, the @file{.dvi}
version of the package's manual is created (to check that the Rd files
can be converted successfully).
@end enumerate

Use @kbd{R CMD check --help} (@kbd{Rcmd check --help} on Windows) to
obtain more information about the usage of the @R{} package checker.
A subset of the checking steps can be selected by
adding flags.

@findex R CMD build
@cindex Package builder
Using @code{R CMD build}, the @R{} package builder, one can build R
packages from their sources (for example, for subsequent release).  The
Windows equivalent is @code{Rcmd build}.

Prior to actually building the package in the common gzipped tar file
format, a variety of diagnostic checks and cleanups are performed.  In
particular, it is tested whether the @file{DESCRIPTION} file contains
the required entries, whether object and data indices exist (it will
build them if they do not) and can be assumed to be up-to-date.

Run-time checks whether the package works correctly should be performed
using @code{R CMD check} prior to invoking the build procedure.

To exclude files from being put into the package, one can specify a list
of exclude patterns in file @file{.Rbuildignore} in the top-level source
directory.  These patterns should be Perl regexps, one per line, to be
matched against the file names relative to the top-level source
directory.  In addition, files called @file{CVS} or @file{GNUMakefile},
or with base names starting with @samp{.#}, or starting and ending with
@samp{#}, or ending in @samp{~} or @samp{.swp}, are excluded by default.

@quotation
@strong{Note:} file exclusion does not work correctly with @acronym{GNU}
@code{tar} 1.13 but does work with later versions (e.g., version
1.13.17).
@end quotation

Use @kbd{R CMD build --help} (@kbd{Rcmd build --help} on Windows) to
obtain more information about the usage of the @R{} package builder.

@code{R CMD build} can also build pre-compiled version of packages for
binary distributions.

@quotation
@strong{Note to Windows users:} @code{Rcmd check} and @code{Rcmd build}
work well under Windows NT4/2000 but may not work correctly on Windows
95/98/ME because of problems with some versions of Perl on those limited
OSes.  Experiences vary.
@end quotation


@node Writing package vignettes, Submitting a package to CRAN, Checking and building packages, Creating R packages
@section Writing package vignettes
@cindex vignettes
@cindex Sweave

In addition to the help files in Rd format, @R{} packages allow the
inclusion of documents in arbitrary other formats.  The standard
location for these is subdirectory @file{inst/doc} of a source package,
the contents will be copied to subdirectory @file{doc} when the package
is installed.  Pointers from package help indices to the installed
documents are automatically created.  Documents in @file{inst/doc} can
be in arbitrary format, however we strongly recommend to provide them in
PDF format, such that users on all platforms can easily read them.

A special case are documents in Sweave format, which we call
@emph{package vignettes}.  Sweave allows to integrate La@TeX{}
documents and @R{} code and is contained in package @pkg{tools} which
is part of the base @R{} distribution, see the @code{Sweave} help page
for details on the document format.  Package vignettes found in
directory @file{inst/doc} are tested by @code{R CMD check} by
executing @emph{all} @R{} code chunks they contain to ensure
consistency between code and documentation.  Note that even code
chunks with option @code{eval=FALSE} are tested, if you want code in a
vignette that should not be tested, move it to a normal LaTeX verbatim
environment. The reason for this policy is that users should be able
to rely on code examples to be executable as seen in the vignette. The
R working directory for all vignette tests in @code{R CMD check} is
the @emph{installed} version of the @file{doc} subdirectory. Make sure
all files needed by the vignette (data sets, @dots{}) are accessible
by either placing them in the @file{inst/doc} hierarchy of the source
package, or using calls to @code{system.file()}.

@code{R CMD build} will automatically create PDF versions of the
vignettes for distribution with the package sources.  By including the
PDF version in the package sources it is not necessary that the
vignettes can be compiled at install time, i.e., the package author can
use private La@TeX{} extensions which are only available on his machine.
Only the @R{} code inside the vignettes is part of the checking
procedure, typesetting manuals is not part of the package QC.

By default @code{R CMD build} will run @code{Sweave} on all files in
Sweave format.  If no @file{Makefile} is found in directory
@file{inst/doc}, then @code{texi2dvi --pdf} is run on all vignettes.
Whenever a @file{Makefile} is found, then @code{R CMD build} will try to
run @command{make} after the @code{Sweave} step, such that PDF manuals
can be created from arbitrary source formats (plain La@TeX{} files,
@dots{}).  The @file{Makefile} should take care of both creation of PDF
files and cleaning up afterwards, i.e., delete all files that shall not
appear in the final package archive.  Note that the @code{make} step is
executed independently from the presence of any files in Sweave format.

It is no longer necessary to provide a @file{00Index.dcf} file in the
@file{inst/doc} directory---the corresponding information is generated
automatically from the @code{\VignetteIndexEntry} statements in all
Sweave files when installing from source, or when using the package
builder (@pxref{Checking and building packages}).  The
@code{\VignetteIndexEntry} statement is best placed in La@TeX{} comment,
such that no definition of the command is necessary.


@node Submitting a package to CRAN, Package name spaces, Writing package vignettes, Creating R packages
@section Submitting a package to @acronym{CRAN}
@cindex CRAN
@cindex CRAN submission
@cindex Submitting to CRAN

@acronym{CRAN} is a network of WWW sites holding the @R{} distributions
and contributed code, especially @R{} packages.  Users of @R{} are
encouraged to join in the collaborative project and to submit their own
packages to @acronym{CRAN}.

Before submitting a package @pkg{mypkg}, do run the following steps to
test it is complete and will install properly.  (Unix procedures only,
run from the directory containing @file{mypkg} as a subdirectory.)

@enumerate
@item
Run @code{R CMD check} to check that the package will install and will
runs its examples, and that the documentation is complete and can be
processed.  If the package contains code that needs to be compiled, try
to enable a reasonable amount of diagnostic messaging (``warnings'') when
compiling, such as e.g.@: @samp{-Wall -pedantic} for tools from GCC, the
Gnu Compiler Collection.  (If @R{} was not configured accordingly, one
can achieve this e.g.@: via @code{PKG_CFLAGS} and related variables.)

@item
Run @code{R CMD build} to run a few further checks and to make the
release @file{.tar.gz} file.
@end enumerate

@noindent
Please ensure that you can run through the complete procedure with only
warnings that you understand and have reasons not to eliminate.

When all the testing is done, upload the @file{.tar.gz} file to

@smallexample
@url{ftp://ftp.ci.tuwien.ac.at/incoming}
@end smallexample

@noindent
and send a message to @url{cran@@r-project.org} about it.  The
@acronym{CRAN} maintainers will run these tests before putting a
submission in the main archive.

Currently, packages containing compiled code should contain at most one
dot in their name to work smoothly under Windows.

Note that the fully qualified name of the @file{.tar.gz} file must be of
the form

@quotation
@file{@var{package}_@var{version}@r{[}_@var{engine}@r{[}_@var{type}@r{]]}},
@end quotation

@noindent
where the @samp{[ ]} indicates that the enclosed component is optional,
@var{package} and @var{version} are the corresponding entries in file
@file{DESCRIPTION}, @var{engine} gives the S engine the package is
targeted for and defaults to @samp{R}, and @var{type} indicated whether
the file contains source or binaries for a certain platform, and
defaults to @samp{source}.  I.e.,

@smallexample
@group
OOP_0.1-3.tar.gz
OOP_0.1-3_R.tar.gz
OOP_0.1-3_R_source.tar.gz
@end group
@end smallexample

@noindent
are all equivalent and indicate an R source package, whereas

@smallexample
OOP_0.1-3_Splus6_sparc-sun-solaris.tar.gz
@end smallexample

@noindent
is a binary package for installation under Splus6 on the given
platform.

This naming scheme has been adopted to ensure usability of code across S
engines.  R code and utilities operating on package @file{.tar.gz} files
can only be assumed to work provided that this naming scheme is
respected.  Of course, @code{R CMD build} automatically creates valid
file names.


@node Package name spaces,  , Submitting a package to CRAN, Creating R packages
@section Package name spaces
@cindex name spaces

@R{} 1.7.0 introduces an experimental name space management system for
packages.  This system allows the package writer to specify which
variables in the package should be @emph{exported} to make them
available to package users, and which variables should be
@emph{imported} from other packages.

The current mechanism@footnote{Alternate approaches are under
consideration and may replace this approach in future @R{} releases.}
for specifying a name space for a package is to place a @file{NAMESPACE}
file in the top level package directory.  This file contains @emph{name
space directives} describing the imports and exports of the name space.
Additional directives register any shared libraries to be loaded and any
S3-style methods that are provided.

Like other packages, packages with name spaces are loaded and attached
to the search path by calling @code{library}.  Only the exported
variables are placed in the attached frame.  Loading a package that
imports variables from other packages will cause these other packages to
be loaded as well (unless they have already been loaded), but they will
@emph{not} be placed on the search path by these implicit loads.

Exports are specified using the @code{export} directive.
A directive of the form

@smallexample
export(f, g)
@end smallexample

@noindent
specifies that the variables @code{f} and @code{g} are to be exported.
(Note that variable names may be quoted, and non-standard names such as
@code{[<-.fractions} must be.)

For packages with many variables to export it may be more convenient to
specify the names to export with a regular expression using
@code{exportPattern}.  The directive

@smallexample
exportPattern("^[^\\.]")
@end smallexample

@noindent
exports all variables that do not start with a period.

All packages implicitly import the base name space.  Variables from
other packages need to be imported explicitly using the directives
@code{import} and @code{importFrom}.  The @code{import} directive
imports all exported variables from the specified package(s).  Thus the
directives

@smallexample
import(foo, bar)
@end smallexample

@noindent
specifies that all exported variables in the packages @pkg{foo} and
@pkg{bar} are to be imported.  If only some of the variables from a
package are needed, then they can be imported using @code{importFrom}.
The directive

@smallexample
importFrom(foo, f, g)
@end smallexample

@noindent
specifies that the exported variables @code{f} and @code{g} of the
package @pkg{foo} are to be imported.

If a package only needs one function from another package it can use a
fully qualified variable reference in the code instead of a formal
import.  A fully qualified reference to the function @code{f} in package
@pkg{foo} is of the form @code{foo::f}.  This is less efficient than a
formal import and also loses the advantage of recording all dependencies
in the @file{NAMESPACE} file, so this approach is usually not
recommended.

The standard method for S3-style @code{UseMethod} dispatching might fail
to locate methods defined in a package that is imported but not attached
to the search path.  To ensure that these methods are available the
packages defining the methods should ensure that the generics are
imported and register the methods using @code{S3method} directives.  If
a package defines a function @code{print.foo} intended to be used as a
@code{print} method for class @code{foo}, then the directive

@smallexample
S3method(print, foo)
@end smallexample

@noindent
ensures that the method is registered and available for @code{UseMethod}
dispatch.  The function @code{print.foo} does not need to be exported.
Since the generic @code{print} is defined in @pkg{base} it does not need
to be imported explicitly.  This mechanism is intended for use with
generics that are defined in a name space.  Any methods for a generic
defined in a package that does not use a name space should be exported,
and the package defining and exporting the method should be attached to
the search path if the methods are to be found.

Packages with name spaces do not use the @code{.First.lib} function.
Since loading and attaching are distinct operations when a name space is
used, separate hooks are provided for each.  These hook functions are
called @code{.onLoad} and @code{.onAttach}.  They take the same
arguments as @code{.First.lib}; they should be defined in the package
but not exported.  Packages are not likely to need @code{.onAttach};
code to set options and load shared libraries should be placed in a
@code{.onLoad} function, or use made of the @code{useDynLib} directive
described next.

The @code{useDynLib} directive allows shared libraries that need to be
loaded to be specified in the @file{NAMESPACE} file.  The directive

@smallexample
useDynLib(foo)
@end smallexample

@noindent
registers the shared library @code{foo} for loading with
@code{library.dynam}.  Loading of registered libraries occurs after the
package code has been loaded and before running the load hook function.
Packages that would only need a load hook function to load a shared
library can use the @code{useDynLib} directive instead.

As an example consider two packages named @pkg{foo} and @pkg{bar}.  The
@R{} code for package @pkg{foo} in file @file{foo.R} is

@quotation
@cartouche
@smallexample
x <- 1
f <- function(y) c(x,y)
foo <- function(x) .Call("foo", x, PACKAGE="foo")
print.foo <- function(x, ...) cat("<a foo>\n")
@end smallexample
@end cartouche
@end quotation

@noindent
Some C code defines a C function compiled into DLL @code{foo} (with an
appropriate extension).  The @file{NAMESPACE} file for this package is

@quotation
@cartouche
@smallexample
useDynLib(foo)
export(f, foo)
S3method(print, foo)
@end smallexample
@end cartouche
@end quotation

@noindent
The second package @pkg{bar} has code file @file{bar.R}

@quotation
@cartouche
@smallexample
c <- function(...) sum(...)
g <- function(y) f(c(y, 7))
h <- function(y) y+9
@end smallexample
@end cartouche
@end quotation

@noindent
and @file{NAMESPACE} file

@quotation
@cartouche
@smallexample
import(foo)
export(g, h)
@end smallexample
@end cartouche
@end quotation

@noindent
Calling @code{library(bar)} loads @pkg{bar} and attaches its exports to
the search path.  Package @pkg{foo} is also loaded but not attached to
the search path.  A call to @code{g} produces

@smallexample
> g(6)
[1]  1 13
@end smallexample

@noindent
This is consistent with the definitions of @code{c} in the two settings:
in @pkg{bar} the function @code{c} is defined to be equivalent to
@code{sum}, but in @pkg{foo} the variable @code{c} refers to the
standard function @code{c} in @pkg{base}.


To summarize, converting an existing package to use a name space involves
several simple steps:

@itemize @bullet
@item Identify the public definitions and place them in @code{export}
      directives.
@item Identify S3-style method definitions and write corresponding
      @code{S3method} declarations.
@item Identify dependencies and replace any @code{require} calls by
      @code{import} directives.
@item Replace @code{.First.lib} functions with @code{.onLoad} functions
      or @code{useDynLib} directives.
@end itemize

@noindent
Some code analysis tools to aid in this process are currently under
development.

Name spaces are @emph{sealed} once they are loaded.  Sealing means that
imports and exports cannot be changed and that internal variable
bindings cannot be changed.  Sealing allows a simpler implementation
strategy for the name space mechanism.  Sealing also allows code
analysis and compilation tools to accurately identify the definition
corresponding to a global variable reference in a function body.

The name space mechanism included in @R{} 1.7.0 does not yet support
code based on the @pkg{methods} package.  Support for @pkg{methods} is
anticipated for the following release of @R{}.


@node Writing R help files, Tidying and profiling R code, Creating R packages, Top
@chapter Writing R help files
@cindex Documentation, writing

@menu
* Rd format::
* Sectioning::
* Marking text::
* Lists and tables::
* Cross-references::
* Mathematics::
* Insertions::
* Platform-specific sections::
* Processing Rd format::
@end menu

@node Rd format, Sectioning, Writing R help files, Writing R help files
@section Rd format

@R{} objects are documented in files written in ``@R{} documentation''
(Rd) format, a simple markup language closely resembling (La)@TeX{},
which can be processed into a variety of formats, including La@TeX{},
@HTML{} and plain text.  The translation is carried out by the Perl
script @command{Rdconv} in @file{@var{R_HOME}/bin} and by the
installation scripts for packages.

The @R{} distribution contains about 1000 such files which can be found
in the @file{src/library/@var{pkg}/man} directories of the @R{} source
tree, where @var{pkg} stands for package @pkg{base} where all the
standard objects are, and for the standard packages such as @pkg{eda}
and @pkg{mva} which are included in the @R{} distribution.

As an example, let us look at the file
@file{src/library/base/man/load.Rd} which documents the @R{} function
@code{load}.

@quotation
@cartouche
@smallexample
\name@{load@}
\alias@{load@}
\title@{Reload Saved Datasets@}
\description@{
  Reload the datasets written to a file with the function
  \code@{save@}.
@}
\usage@{
load(file, envir = parent.frame())
@}
\arguments@{
  \item@{file@}@{a connection or a character string giving the
    name of the file to load.@}
  \item@{envir@}@{the environment where the data should be
    loaded.@}
@}
\seealso@{
  \code@{\link@{save@}@}.
@}
\examples@{
## save all data
save(list = ls(), file= "all.Rdata")

## restore the saved values to the current environment
load("all.Rdata")

## restore the saved values to the workspace
load("all.Rdata", .GlobalEnv)
@}
\keyword@{file@}
@end smallexample
@end cartouche
@end quotation

An Rd file consists of three parts.  The header gives basic information
about the name of the file, the topics documented, a title, a short
textual description and @R{} usage information for the objects
documented.  The body gives further information (for example, on the
function's arguments and return value, as in the above example).
Finally, there is a footer with keyword information.  The header and
footer are mandatory.

See the @uref{http://developer.r-project.org/Rds.html, ``Guidelines for Rd
files''} for guidelines for writing documentation in Rd format which
should be useful for package writers.

@subsection Documenting functions

The basic markup commands used for documenting @R{} objects (in
particular, functions) are given in this subsection.

@table @code
@item \name@{@var{name}@}
@findex \name
@var{name} typically is the basename of the Rd file containing the
documentation.  (It is the ``name'' of the Rd object represented by the
file, and has to be unique in a package.)

@item \alias@{@var{topic}@}
@findex \alias
The @code{\alias} entries specify all ``topics'' the file documents.
This information is collected into index data bases for lookup by the
on-line (plain text and @HTML{}) help systems.

There may be several @code{\alias} entries.  Quite often it is
convenient to document several @R{} objects in one file.  For example,
file @file{Normal.Rd} documents the density, distribution function,
quantile function and generation of random variates for the normal
distribution, and hence starts with

@smallexample
@group
\name@{Normal@}
\alias@{dnorm@}
\alias@{pnorm@}
\alias@{qnorm@}
\alias@{rnorm@}
@end group
@end smallexample

Note that the @code{\name} is not necessarily a topic documented.

@item \title@{@var{Title}@}
@findex \title
Title information for the Rd file.  This should be capitalized, not end
in a period, and not use any markup (which would cause problems for
hypertext search).

@item \description@{@dots{}@}
@findex \description
A short description of what the function(s) do(es) (one paragraph, a few
lines only).  (If a description is ``too long'' and cannot easily be
shortened, the file probably tries to document too much at once.)

@item \usage@{@var{fun}(@var{arg1}, @var{arg2}, @dots{})@}
@findex \usage
One or more lines showing the synopsis of the function(s) and variables
documented in the file.  These are set verbatim in typewriter font.

The usage information specified should in general match the function
definition @emph{exactly} (such that automatic checking for consistency
between code and documentation is possible).  Otherwise, include a
@code{\synopsis}
@findex \synopsis
section with the actual definition.

For example, @code{abline} is a function for adding a straight line to a
plot which can be used in several different ways, depending on the named
arguments specified.  Hence, @file{abline.Rd} contains

@smallexample
@group
\synopsis@{
abline(a = NULL, b = NULL, h = NULL, v = NULL, reg = NULL,
       coef = NULL, untf = FALSE, col = par("col"),
       lty = par("lty"), lwd = NULL, ...)
@}
\usage@{
abline(a, b, \dots)
abline(h=, \dots)
abline(v=, \dots)
@r{@dots{}}
@}
@end group
@end smallexample

@findex \method
Use @code{\method@{@var{generic}@}@{@var{class}@}} to indicate the name
of an S3 method for the generic function @var{generic} for objects
inheriting from class @code{"@var{class}"}.  In the printed versions,
this will come out as @var{generic} (reflecting the understanding that
methods should not be invoked directly but via method dispatch), but
@code{codoc()} and other QC tools always have access to the full name.

For example, @file{print.ts.Rd} contains

@smallexample
@group
\usage@{
\method@{print@}@{ts@}(x, calendar, \dots)
@}
@end group
@end smallexample

@item \arguments@{@dots{}@}
@findex \arguments
Description of the function's arguments, using an entry of the form

@smallexample
\item@{@var{arg_i}@}@{@var{Description of arg_i}.@}
@end smallexample

@noindent
for each element of the argument list.  There may be optional text
before and after these entries.

@item \details@{@dots{}@}
@findex \details
A detailed if possible precise description of the functionality
provided, extending the basic information in the @code{\description}
slot.

@item \value@{@dots{}@}
@findex \value
Description of the function's return value.

If a list with multiple values is returned, you can use entries of the
form

@smallexample
\item@{@var{comp_i}@}@{@var{Description of comp_i}.@}
@end smallexample

@noindent
for each component of the list returned.  Optional text may precede this
list (see the introductory example for @code{rle}).

@item \references@{@dots{}@}
@findex \references
A section with references to the literature.  Use @code{\url@{@}} for
web pointers.

@item \note@{...@}
@findex \note
Use this for a special note you want to have pointed out.

For example, @file{pie.Rd} contains

@smallexample
@group
\note@{
  Pie charts are a very bad way of displaying information.
  The eye is good at judging linear measures and bad at
  judging relative areas.
  ...
@}
@end group
@end smallexample

@item \author@{@dots{}@}
@findex \author
Information about the author(s) of the Rd file.  Use @code{\email@{@}}
without extra delimiters (@samp{( )} or @samp{< >}) to specify email
addresses, or @code{\url@{@}} for web pointers.

@item \seealso@{@dots{}@}
@findex \seealso
Pointers to related @R{} objects, using @code{\code@{\link@{...@}@}} to
refer to them (@code{\code} is the correct markup for @R{} object names,
and @code{\link}
@findex \link
produces hyperlinks in output formats which support this.  @xref{Marking
text}, and @ref{Cross-references}).

@findex \examples
@item \examples@{@dots{}@}
Examples of how to use the function.  These are set verbatim in
typewriter font.

Examples are not only useful for documentation purposes, but also
provide test code used for diagnostic checking of @R{}.  By default,
text inside @code{\examples@{@}} will be displayed in the output of the
help page and run by @code{R CMD check}.  You can use
@code{\dontrun@{@}}
@findex \dontrun
for commands that should only be shown, but not run, and
@code{\testonly@{@}}
@findex \testonly
for extra commands for testing that should not be shown to users.

For example,

@smallexample
@group
x <- runif(10)       # @r{Shown and run.}
\dontrun@{plot(x)@}    # @r{Only shown.}
\testonly@{log(x)@}    # @r{Only run.}
@end group
@end smallexample

Thus, example code not included in @code{\dontrun} must be executable!
In addition, it should not use any system-specific features or require
special facilities (such as Internet access or write permission to
specific directories).

Data needed for making the examples executable can be obtained by random
number generation (for example, @code{x <- rnorm(100)}), or by using
standard data sets loadable via @code{data()} (see @code{?data} for more
info).

@item \keyword@{@var{key}@}
Each @code{\keyword} entry should specify one of the standard keywords
(as listed in the file @file{@var{R_HOME}/doc/KEYWORDS.db}).  There must
be at least one @code{\keyword} entry, but can be more that one if the
@R{} object being documented falls into more than one category.

The special keyword @samp{internal} marks a page of internal objects
that are not part of the packages' API. If the help page for object
@code{foo} has keyword @samp{internal}, then @code{help(foo)} gives this
help page, but @code{foo} is excluded from several object indices, like
the alphabetical list of objects in the @HTML{} help system.
@end table

@findex prompt
The @R{} function @code{prompt} facilitates the construction of files
documenting @R{} objects.  If @code{foo} is an @R{} function, then
@kbd{prompt(foo)} produces file @file{foo.Rd} which already contains
the proper function and argument names of @code{foo}, and a structure
which can be filled in with information.

@subsection Documenting datasets

The structure of Rd files which document @R{} data sets is slightly
different.  Whereas sections such as @code{\arguments} and @code{\value}
are not needed, the format and source of the data should be explained.

As an example, let us look at @file{src/library/base/man/rivers.Rd}
which documents the standard @R{} data set @code{rivers}.

@quotation
@cartouche
@smallexample
\name@{rivers@}
\docType@{data@}
\alias@{rivers@}
\title@{Lengths of Major North American Rivers@}
\description@{
  This data set gives the lengths (in miles) of 141 ``major''
  rivers in North America, as compiled by the US Geological
  Survey.
@}
\usage@{data(rivers)@}
\format@{A vector containing 141 observations.@}
\source@{World Almanac and Book of Facts, 1975, page 406.@}
\references@{
  McNeil, D. R. (1977) \emph@{Interactive Data Analysis@}.
  New York: Wiley.
@}
\keyword@{datasets@}
@end smallexample
@end cartouche
@end quotation

This uses the following additional markup commands.

@table @code
@item \docType@{@dots{}@}
Indicates the ``type'' of the documentation object.  Always @samp{data}
for data sets.

@item \format@{@dots{}@}
@findex \format
A description of the format of the dataset (as a vector, matrix, data
frame, time series, @dots{}).  For matrices and data frames this should
give a description of each column, preferably as a list or table.
@xref{Lists and tables}, for more information.

@item \source@{@dots{}@}
@findex \source
Details of the original source (a reference or @acronym{URL}).  In
addition, section @code{\references} could give secondary sources and
usages.
@end table

Note also that when documenting data set @var{bar},

@itemize @bullet
@item
The @code{\usage} entry is always @code{data(@var{bar})}.  (In
particular, only document a @emph{single} data object per Rd file.)
@item
The @code{\keyword} entry is always @samp{datasets}.
@end itemize

If @code{bar} is a data frame, documenting it as a data set can again be
initiated via @kbd{prompt(bar)}.

@node Sectioning, Marking text, Rd format, Writing R help files
@section Sectioning

To begin a new paragraph or leave a blank line in an example, just
insert an empty line (as in (La)@TeX{}).  To break a line, use
@code{\cr}.
@findex \cr

In addition to the predefined sections (such as @code{\description@{@}},
@code{\value@{@}}, etc.), you can ``define'' arbitrary ones by
@code{\section@{@var{section_title}@}@{@dots{}@}}.
@findex \section
For example

@display
@code{\section@{Warning@}@{You must not call this function unless @dots{}@}}
@end display

@noindent
For consistency with the pre-assigned sections, the section name (the
first argument to @code{\section}) should be capitalized (but not all
upper case).

Note that the additional named sections are always inserted at fixed
positions in the output (before @code{\note}, @code{\seealso} and the
examples), no matter where they appear in the input.

@node Marking text, Lists and tables, Sectioning, Writing R help files
@section Marking text
@cindex Marking text in documentation

The following logical markup commands are available for indicating
specific kinds of text.

@quotation
@multitable @columnfractions .20 .70
@item @code{\bold@{@var{word}@}}
@findex \bold
@tab set @var{word} in @strong{bold} font if possible
@item @code{\emph@{@var{word}@}}
@findex \emph
@tab emphasize @var{word} using @emph{italic} font if possible
@item @code{\code@{@var{word}@}}
@findex \code
@tab for pieces of code, using @code{typewriter} font if possible
@item @code{\file@{@var{word}@}}
@findex \file
@tab for file names
@item @code{\email@{@var{word}@}}
@findex \email
@tab for email addresses
@item @code{\url@{@var{word}@}}
@findex \url
@tab for @acronym{URL}s
@end multitable
@end quotation

@noindent The first two, @code{\bold} and @code{\emph}, should be used
in plain text for emphasis.

Fragments of @R{} code, including the names of @R{} objects, should be
marked using @code{\code}.  Only backslashes and percent signs need to
be escaped (by a backslash) inside @code{\code}.

@node Lists and tables, Cross-references, Marking text, Writing R help files
@section Lists and tables
@cindex Lists and tables in documentation

@findex \itemize
@findex \enumerate
The @code{\itemize} and @code{\enumerate} commands take a single
argument, within which there may be one or more @code{\item} commands.
The text following each @code{\item} is formatted as one or more
paragraphs, suitably indented and with the first paragraph marked with a
bullet point (@code{\itemize}) or a number (@code{\enumerate}).

@code{\itemize} and @code{\enumerate} commands may be nested.

@findex \describe
The @code{\describe} command is similar to @code{\itemize} but allows
initial labels to be specified.  The @code{\item}s take two arguments,
the label and the body of the item, in exactly the same way as argument
and value @code{\item}s.  @code{\describe} commands are mapped to
@code{<DL>} lists in @HTML{} and @code{\description} lists in La@TeX{}.

@findex \tabular
The @code{\tabular} command takes two arguments.  The first gives for
each of the columns the required alignment (@samp{l} for
left-justification, @samp{r} for right-justification or @samp{c} for
centering.)  The second argument consists of an arbitrary number of
lines separated by @code{\cr}, and with fields separated by @code{\tab}.
For example:

@smallexample
@group
  \tabular@{rlll@}@{
    [,1] \tab Ozone   \tab numeric \tab Ozone (ppb)\cr
    [,2] \tab Solar.R \tab numeric \tab Solar R (lang)\cr
    [,3] \tab Wind    \tab numeric \tab Wind (mph)\cr
    [,4] \tab Temp    \tab numeric \tab Temperature (degrees F)\cr
    [,5] \tab Month   \tab numeric \tab Month (1--12)\cr
    [,6] \tab Day     \tab numeric \tab Day of month (1--31)
  @}
@end group
@end smallexample

@noindent
There must be the same number of fields on each line as there are
alignments in the first argument, and they must be non-empty (but can
contain only spaces).

@node Cross-references, Mathematics, Lists and tables, Writing R help files
@section Cross-references
@cindex Cross-references in documentation

The markup @code{\link@{@var{foo}@}} (usually in the combination
@code{\code@{\link@{@var{foo}@}@}}) produces a hyperlink to the help
page for object @var{foo}.  One main usage of @code{\link} is in the
@code{\seealso} section of the help page, @pxref{Rd format}.  (This only
affects the creation of hyperlinks, for example in the @HTML{} pages
used by @code{help.start()} and the PDF version of the reference
manual.)

There are optional arguments specified as
@code{\link[@var{pkg}]@{@var{foo}@}} and
@code{\link[@var{pkg:bar}]@{@var{foo}@}} to link to the package
@var{pkg} with topic (file?) @var{foo} and @var{bar} respectively.

@node Mathematics, Insertions, Cross-references, Writing R help files
@section Mathematics
@cindex Mathematics in documentation
@findex \eqn
@findex \deqn

Mathematical formulae should be set beautifully for printed
documentation yet we still want something useful for text and @HTML{}
online help.  To this end, the two commands
@code{\eqn@{@var{latex}@}@{@var{ascii}@}} and
@code{\deqn@{@var{latex}@}@{@var{ascii}@}} are used.  Where @code{\eqn}
is used for ``inline'' formulae (corresponding to @TeX{}'s
@code{$@dots{}$}, @code{\deqn} gives ``displayed equations'' (as in
La@TeX{}'s @code{displaymath} environment, or @TeX{}'s
@code{$$@dots{}$$}).

Both commands can also be used as @code{\eqn@{@var{latexascii}@}} (only
@emph{one} argument) which then is used for both @var{latex} and
@var{ascii}.

The following example is from @file{Poisson.Rd}:

@smallexample
@group
  \deqn@{p(x) = \frac@{\lambda^x e^@{-\lambda@}@}@{x!@}@}@{%
        p(x) = lambda^x exp(-lambda)/x!@}
  for \eqn@{x = 0, 1, 2, \ldots@}.
@end group
@end smallexample

@iftex
For the La@TeX{} manual, this becomes

@quotation
@cartouche
@tex
$$ p(x) = \lambda^x\ {e^{-\lambda} \over x!} $$
for $x = 0, 1, 2, \ldots$.
@end tex
@end cartouche
@end quotation
@end iftex

For @HTML{} and text on-line help we get

@quotation
@cartouche
@smallexample
    p(x) = lambda^x exp(-lambda)/x!

for x = 0, 1, 2, ....
@end smallexample
@end cartouche
@end quotation

@c  For historic reasons mostly, the @TeX{}/La@TeX{} commands @code{\alpha},
@c  @code{\Alpha}, @code{\beta}, @code{\Gamma}, @code{\epsilon},
@c  @code{\lambda}, @code{\mu}, @code{\pi}, @code{\sigma}, @code{\left(} and
@c  @code{\right)} exist.  These can be used directly, without using the
@c  @code{\eqn} diversion.
@c  @findex \alpha
@c  @findex \Alpha
@c  @findex \beta
@c  @findex \Gamma
@c  @findex \epsilon
@c  @findex \lambda
@c  @findex \mu
@c  @findex \pi
@c  @findex \sigma
@c  @findex \left(
@c  @findex \right)

@node Insertions, Platform-specific sections, Mathematics, Writing R help files
@section Insertions

@findex \R
Use @code{\R} for the @R{} system itself (you don't need extra
@samp{@{@}} or @samp{\}).  Use @code{\dots}
@findex \dots
for the dots in function argument lists @samp{@dots{}}, and
@code{\ldots}
@findex \ldots
for ellipsis dots in ordinary text.

After a @samp{%}, you can put your own comments regarding the help text.
The rest of the line will be completely disregarded, normally.
Therefore, you can also use it to make part of the ``help'' invisible.

You can produce a backslash (@samp{\}) by escaping it by another
backslash.  (Note that @code{\cr} is used for generating line breaks.)

The ``comment'' and ``control'' characters @samp{%} and @samp{\}
@emph{always} need to be escaped.  Inside the verbatim-like commands
(@code{\code} and @code{\examples}), no other@footnote{This is not quite
true.  Unpaired braces will give problems and should be escaped.  See
the examples section in the file @file{Paren.Rd} for an example.}
characters are special.  Note that @code{\file} is @strong{not} a
verbatim-like command.

In ``regular'' text (no verbatim, no @code{\eqn}, @dots{}), you
currently must escape most La@TeX{} special characters, i.e., besides
@samp{%}, @samp{@{}, and @samp{@}}, the four specials @samp{$},
@samp{#}, and @samp{_} are produced by preceding each with a @samp{\}.
(@samp{&} can also be escaped, but need not be.) Further, enter @samp{^}
as @code{\eqn@{\mbox@{\textasciicircum@}@}@{^@}}, and @samp{~} by
@code{\eqn@{\mbox@{\textasciitilde@}@}@{~@}} or @code{\eqn@{\sim@}@{~@}}
(for a short and long tilde respectively).  Also, @samp{<}, @samp{>},
and @samp{|} must only be used in math mode, i.e., within @code{\eqn} or
@code{\deqn}.

@node  Platform-specific sections, Processing Rd format, Insertions, Writing R help files
@section Platform-specific documentation
@cindex Platform-specific documentation

Sometimes the documentation needs to differ by platform.  Currently
three OS-specific options are available, @samp{unix}, @samp{windows} and
@samp{mac}, and lines in the help source file can be enclosed in

@smallexample
@group
#ifdef @var{OS}
   ...
#endif
@end group
@end smallexample

@noindent
or

@smallexample
@group
#ifndef @var{OS}
   ...
#endif
@end group
@end smallexample

@noindent
for OS-specific inclusion or exclusion.

If the differences between platforms are extensive or the @R{} objects
documented are only relevant to one platform, platform-specific Rd files
can be put in a @file{unix}, @file{windows} or @file{mac} subdirectory.

@node Processing Rd format,  , Platform-specific sections, Writing R help files
@section Processing Rd format
@cindex Processing Rd format

Under UNIX versions of @R{} there are several commands to process Rd
files.  Windows equivalents are described at the end of the section.
All of these need Perl to be installed.

@findex R CMD Rdconv
Using @code{R CMD Rdconv} one can convert @R{} documentation format to
other formats, or extract the executable examples for run-time testing.
Currently, conversions to plain text, @HTML{}, La@TeX{}, and @Sl{}
version 3 or 4 documentation formats are supported.

In addition to this low-level conversion tool, the @R{} distribution
provides two user-level programs for processing Rd format.
@findex R CMD Rd2txt
@findex R CMD Rd2dvi
@code{R CMD Rd2txt} produces ``pretty'' plain text output from an Rd
file, and is particularly useful as a previewer when writing Rd format
documentation within Emacs.  @code{R CMD Rd2dvi} generates DVI (or, if
option @option{--pdf} is given, PDF) output from documentation in Rd
files, which can be specified either explicitly or by the path to a
directory with the sources of a package (or bundle).  In the latter
case, a reference manual for all documented objects in the package is
created, including the information in the @file{DESCRIPTION} files.

@findex R CMD Sd2Rd
Finally, @code{R CMD Sd2Rd} converts @Sl{} version 3 documentation files
(which use an extended Nroff format) and @Sl{} version 4 documentation
(which uses SGML markup) to Rd format.  This is useful when porting a
package originally written for the @Sl{} system to @R{}.  @Sl{} version
3 files usually have extension @file{.d}, whereas version 4 ones have
extension @file{.sgml} or @file{.sgm}.

The exact usage and a detailed list of available options for each of the
above commands can be obtained by running @code{R CMD @var{command}
--help}, e.g., @kbd{R CMD Rdconv --help}.  All available commands can be
listed using @kbd{R --help}.

All of these have Windows equivalents.  For most just replace @samp{R
CMD} by @samp{Rcmd}, with the exception that it is @code{Rcmd Rd2dvi.sh}
(and that needs the tools to build packages from source to be
installed).  (You will need the files in the @R{} binary Windows
distribution for installing source packages to be installed.)

@node Tidying and profiling R code, System and foreign language interfaces, Writing R help files, Top
@chapter Tidying and profiling R code

@menu
* Tidying R code::
* Profiling R code::
@end menu

@R{} code which is worth preserving in a package and perhaps making
available for others to use is worth documenting, tidying up and perhaps
optimizing. The last two of these activities are the subject of this
chapter.

@node Tidying R code, Profiling R code, Tidying and profiling R code, Tidying and profiling R code
@section Tidying R code
@cindex Tidying R code

@R{} treats function code loaded from packages and code entered by users
differently.  Code entered by users has the source code stored in an
attribute, and when the function is listed, the original source is
reproduced.  Loading code from a package (by default) discards the
source code, and the function listing is re-created from the parse tree
of the function.

Normally keeping the source code is a good idea, and in particular it
avoids comments being moved around in the source.  However, we can make
use of the ability to re-create a function listing from its parse tree
to produce a tidy version of the function, with consistent indentation,
spaces around operators and consistent use of the preferred assignment
operator @samp{<-}.  This tidied version is much easier to read, not
least by other users who are used to the standard format.

We can subvert the keeping of source in two ways.

@enumerate
@item
The option @code{keep.source} can be set to @code{FALSE} before the code
is loaded into @R{}.
@item
The stored source code can be removed by removing the @code{source}
attribute, for example by

@smallexample
attr(myfun, "source") <- NULL
@end smallexample

@end enumerate

@noindent
In each case if we then list the function we will get the standard
layout.

Suppose we have a file of functions @file{myfuns.R} that we want to
tidy up.  Create a file @file{tidy.R} containing

@smallexample
@group
options(keep.source = FALSE)
source("myfuns.R")
dump(ls(all = TRUE), file = "new.myfuns.R")
@end group
@end smallexample

@noindent
and run @R{} with this as the source file, for example by @kbd{R
--vanilla < tidy.R} (Unix) or @kbd{Rterm --vanilla < tidy.R} (Windows)
or by pasting into an @R{} session.  Then the file @file{new.myfuns.R}
will contain the functions in alphabetical order in the standard layout.
You may need to move comments to more appropriate places.

The standard format provides a good starting point for further tidying.
Most package authors use a version of Emacs (on Unix or Windows) to edit
@R{} code, using the ESS[S] mode of the @acronym{ESS} Emacs package.
See @ref{R coding standards} for style options within the ESS[S] mode
recommended for the source code of @R{} itself.


@node Profiling R code,  , Tidying R code, Tidying and profiling R code
@section Profiling R code
@cindex Profiling
@findex Rprof

It is possible to profile @R{} code on most Unix-like versions of @R{},
@R{} has to be built to enable this, by supplying the option
@option{--enable-R-profiling}, profiling being enabled in a default
build.  Profiling is also available on Windows, but not on the Macintosh.

The command @command{Rprof} is used to control profiling, and its help
page can be consulted for full details.  Profiling works by recording at
fixed intervals (by default every 20 msecs) which @R{} function is being
used, and recording the results in a file (default @file{Rprof.out} in
the working directory).  Then the function @code{summaryRprof} or the
command-line utility @code{R CMD Rprof @var{Rprof.out}} can be used to summarize the
activity.

As an example, consider the following code (from Venables & Ripley,
1999).

@smallexample
@group
library(MASS); library(boot); library(nls)
data(stormer)
storm.fm <- nls(Time ~ b*Viscosity/(Wt - c), stormer,
                start = c(b=29.401, c=2.2183))
st <- cbind(stormer, fit=fitted(storm.fm))
storm.bf <- function(rs, i) @{
    st$Time <-  st$fit + rs[i]
    tmp <- nls(Time ~ (b * Viscosity)/(Wt - c), st,
               start = coef(storm.fm))
    tmp$m$getAllPars()
@}
rs <- scale(resid(storm.fm), scale = FALSE) # remove the mean
Rprof("boot.out")
storm.boot <- boot(rs, storm.bf, R = 4999) # pretty slow
Rprof(NULL)
@end group
@end smallexample

@noindent
Having run this we can summarize the results by

@smallexample
@group
R CMD Rprof boot.out

Each sample represents 0.02 seconds.
Total run time: 80.74 seconds.

Total seconds: time spent in function and callees.
Self seconds: time spent in function alone.
@end group

@group
   %       total       %       self
 total    seconds     self    seconds    name
100.00     80.74      0.22      0.18     "boot"
 99.65     80.46      1.19      0.96     "statistic"
 96.33     77.78      2.68      2.16     "nls"
 50.21     40.54      1.54      1.24     "<Anonymous>"
 47.11     38.04      1.83      1.48     ".Call"
 23.06     18.62      2.43      1.96     "eval"
 19.87     16.04      0.67      0.54     "as.list"
 18.97     15.32      0.64      0.52     "switch"
 17.88     14.44      0.47      0.38     "model.frame"
 17.41     14.06      1.73      1.40     "model.frame.default"
 17.41     14.06      2.80      2.26     "nlsModel"
 15.43     12.46      1.88      1.52     "qr.qty"
 13.40     10.82      3.07      2.48     "assign"
 12.73     10.28      2.33      1.88     "storage.mode<-"
 12.34      9.96      1.81      1.46     "qr.coef"
 10.13      8.18      5.42      4.38     "paste"
  ...
@end group

@group
   %       self        %       total
 self     seconds    total    seconds    name
  5.42      4.38     10.13      8.18     "paste"
  3.37      2.72      6.71      5.42     "as.integer"
  3.29      2.66      5.00      4.04     "as.double"
  3.20      2.58      4.29      3.46     "seq.default"
  3.07      2.48     13.40     10.82     "assign"
  2.92      2.36      5.95      4.80     "names"
  2.80      2.26     17.41     14.06     "nlsModel"
  2.68      2.16     96.33     77.78     "nls"
  2.53      2.04      2.53      2.04     ".Fortran"
  2.43      1.96     23.06     18.62     "eval"
  2.33      1.88     12.73     10.28     "storage.mode<-"
  ...
@end group
@end smallexample

@noindent
This often produces surprising results and can be used to identify
bottlenecks or pieces of @R{} code that could benefit from being
replaced by compiled code.

@code{R CMD Rprof} (or @code{Rcmd Rprof} under Windows) uses a Perl
script that may be much faster than @code{summaryRprof} for large files
(about 4 times faster for the example above). On the other hand
@code{summaryRprof} does not require Perl and provides the results as an
@R{} object.

Two warnings: profiling does impose a small performance penalty, and the
output files can be very large if long runs are profiled.

@node System and foreign language interfaces, The R API, Tidying and profiling R code, Top
@chapter System and foreign language interfaces

@menu
* Operating system access::
* Interface functions .C and .Fortran::
* dyn.load and dyn.unload::
* Registering native routines::
* Creating shared libraries::
* Interfacing C++ code::
* Handling R objects in C::
* Interface functions .Call and .External::
* Evaluating R expressions from C::
* Debugging::
@end menu

@node  Operating system access, Interface functions .C and .Fortran, System and foreign language interfaces, System and foreign language interfaces
@section  Operating system access
@cindex Operating system access

Access to operating system functions is via the @R{} function
@code{system}.
@findex system
The details will differ by platform (see the on-line help), and about
all that can safely be assumed is that the first argument will be a
string @code{command} that will be passed for execution (not necessarily
by a shell) and the second argument will be @code{internal} which if
true will collect the output of the command into an @R{} character
vector.

The function @code{system.time}
@findex system.time
is available for timing (although the information available may be
limited on non-Unix-like platforms).

@node Interface functions .C and .Fortran, dyn.load and dyn.unload, Operating system access, System and foreign language interfaces
@section Interface functions @code{.C} and @code{.Fortran}
@cindex Interfaces to compiled code

@findex .C
@findex .Fortran

These two functions provide a standard interface to compiled code that
has been linked into @R{}, either at build time or via @code{dyn.load}
(@pxref{dyn.load and dyn.unload}).  They are primarily intended for
compiled C and FORTRAN code respectively, but the @code{.C} function can
be used with other languages which can generate C interfaces, for
example C++ (@pxref{Interfacing C++ code}).

The first argument to each function is a character string given the
symbol name as known to C or FORTRAN, that is the function or subroutine
name.  (The mapping to the symbol name in the load table is given by the
functions @code{symbol.C} and @code{symbol.For};
@findex symbol.C
@findex symbol.For
that the symbol is loaded can be tested by, for example,
@code{is.loaded(symbol.C("loglin"))}.)

There can be up to 65 further arguments giving @R{} objects to be passed
to compiled code.  Normally these are copied before being passed in, and
copied again to an @R{} list object when the compiled code returns.  If
the arguments are given names, these are used as names for the
components in the returned list object (but not passed to the compiled
code).

The following table gives the mapping between the modes of @R{} vectors
and the types of arguments to a C function or FORTRAN subroutine.

@quotation
@multitable {RRR storage.mode} {RRR storage.mode} {DOUBLE PRECISION}

@item @R{} storage mode @tab  C type  @tab   FORTRAN type

@item @code{logical}   @tab @code{int *}     @tab @code{INTEGER}
@item @code{integer}   @tab @code{int *}     @tab @code{INTEGER}
@item @code{double}    @tab @code{double *}  @tab @code{DOUBLE PRECISION}
@item @code{complex}   @tab @code{Rcomplex *} @tab @code{DOUBLE COMPLEX}
@item @code{character} @tab @code{char **}   @tab @code{CHARACTER*255}

@end multitable
@end quotation

C type @code{Rcomplex} is a structure with @code{double} members
@code{r} and @code{i} defined in the header file @file{Complex.h}
included by @file{R.h}.  Only a single character string can be passed to
or from FORTRAN, and the success of this is compiler-dependent.  Other
@R{} objects can be passed to @code{.C}, but it is better to use one of
the other interfaces.  An exception is passing an @R{} function for use
with @w{@code{call_R}}, when the object can be handled as @code{void *}
en route to @code{call_R}, but even there @code{.Call} is to be
preferred.  Similarly, passing an R list as an argument to a C routine
should be done using the @code{.Call} interface.  If one does use the
@code{.C} function to pass a list as an argument, it is visible to the
routine as an array in C of @code{SEXP} types (i.e., @code{SEXP *}).
The elements of the array correspond directly to the elements of the R
list.  However, this array must be treated as read-only and one must not
assign values to its elements within the C routine.  Doing so bypasses
R's memory management facilities and will corrupt the object and the R
session.

It is possible to pass numeric vectors of storage mode @code{double} to
C as @code{float *} or FORTRAN as @code{REAL} by setting the attribute
@code{Csingle}, most conveniently by using the @R{} functions
@code{as.single}, @code{single} or @code{storage.mode}.  This is
intended only to be used to aid interfacing to existing C or FORTRAN
code.

Unless formal argument @code{NAOK} is true, all the other arguments are
checked for missing values @code{NA} and for the @acronym{IEEE} special
values @code{NaN}, @code{Inf} and @code{-Inf}, and the presence of any
of these generates an error.  If it is true, these values are passed
unchecked.

Argument @code{DUP} can be used to suppress copying.  It is dangerous:
see the on-line help for arguments against its use.  It is not possible
to pass numeric vectors as @code{float *} or @code{REAL} if
@code{DUP=FALSE}.

Finally, argument @code{PACKAGE} confines the search for the symbol name
to a specific shared library (or use @code{"base"} for code compiled
into @R{}).  Its use is highly desirable, as there is no way to avoid
two package writers using the same symbol name, and such name clashes
are normally sufficient to cause @R{} to crash.

Note that the compiled code should not return anything except through
its arguments: C functions should be of type @code{void} and FORTRAN
subprograms should be subroutines.

To fix ideas, let us consider a very simple example which convolves two
finite sequences. (This is hard to do fast in interpreted @R{} code, but
easy in C code.)  We could do this using @code{.C} by

@smallexample
@group
void convolve(double *a, int *na, double *b, int *nb, double *ab)
@{
  int i, j, nab = *na + *nb - 1;

  for(i = 0; i < nab; i++)
    ab[i] = 0.0;
  for(i = 0; i < *na; i++)
    for(j = 0; j < *nb; j++)
      ab[i + j] += a[i] * b[j];
@}
@end group
@end smallexample

@noindent
called from @R{} by

@smallexample
@group
conv <- function(a, b)
  .C("convolve",
     as.double(a),
     as.integer(length(a)),
     as.double(b),
     as.integer(length(b)),
     ab = double(length(a) + length(b) - 1))$ab
@end group
@end smallexample

Note that we take care to coerce all the arguments to the correct @R{}
storage mode before calling @code{.C}; mistakes in matching the types
can lead to wrong results or hard-to-catch errors.


@node dyn.load and dyn.unload, Registering native routines, Interface functions .C and .Fortran, System and foreign language interfaces
@section @code{dyn.load} and @code{dyn.unload}
@cindex Dynamic loading

@findex dyn.load
@findex dyn.unload

Compiled code to be used with @R{} is loaded as a shared library (Unix,
@pxref{Creating shared libraries} for more information) or DLL
(Windows).

The library/DLL is loaded by @code{dyn.load} and unloaded by
@code{dyn.unload}.  Unloading is not normally necessary, but it is
needed to allow the DLL to be re-built on some platforms, including
Windows.

The first argument to both functions is a character string giving the
path to the library.  Programmers should not assume a specific file
extension for the library (such as @samp{.so}) but use a construction
like

@smallexample
file.path(path1, path2, paste("mylib", .Platform$dynlib.ext, sep=""))
@end smallexample

@noindent
for platform independence.  On Unix systems the path supplied to
@code{dyn.load} can be an absolute path, one relative to the current
directory or, if it starts with @samp{~}, relative to the user's home
directory.

Loading is most often done via a call to @code{library.dynam}
@findex library.dynam
in the @code{.First.lib} function of a package.  This has the form

@smallexample
library.dynam("libname", package, lib.loc)
@end smallexample

@noindent
where @code{libname} is the library/DLL name @emph{with the extension
omitted}.

Under some Unix systems there is a choice of how the symbols are
resolved when the library is loaded, governed by the arguments
@code{local} and @code{now}.  Only use these if really necessary: in
particular using @code{now=FALSE} and then calling an unresolved symbol
will terminate @R{} unceremoniously.

R provides a way of executing some code automatically when a library/DLL
is either loaded or unloaded.  This can be used, for example, to
register native routines with R's dynamic symbol mechanism, initialize
some data in the native code, or initialize a third party library.  On
loading a DLL, R will look for a routine within that DLL named
@code{R_init_@var{lib}} where @var{lib} is the name of the DLL file with
the extension removed.  For example, in the command

@smallexample
library.dynam("mylib", package, lib.loc)
@end smallexample

@noindent
R looks for the symbol named @code{R_init_mylib}.  Similarly, when
unloading the library, R looks for a routine named
@code{R_unload_@var{lib}}, e.g., @code{R_unload_mylib}.  In either case,
if the routine is present, R will invoke it and pass it a single
argument describing the DLL.  This is a value of type @code{DllInfo}
which is defined in the @file{Rdynload.h} file in the @file{R_ext}
directory.

The following example shows templates for the initialization and
unload routines for the @code{mylib} DLL.

@cartouche
@smallexample
#include <Rdefines.h>
#include <R_ext/Rdynload.h>

void
R_init_mylib(DllInfo *info)
@{
  /* Register routines, allocate resources. */
@}

void
R_unload_mylib(DllInfo *info)
@{
  /* Release resources. */
@}
@end smallexample
@end cartouche

If a library/DLL is loaded more than once the most recent version is
used.  More generally, if the same symbol name appears in several
libraries, the most recently loaded occurrence is used.  The
@code{PACKAGE} argument provides a good way to avoid any ambiguity in
which occurrence is meant.


@node Registering native routines, Creating shared libraries, dyn.load and dyn.unload, System and foreign language interfaces
@section Registering native routines
@cindex Registering native routines

In calls to @code{.C}, @code{.Call}, @code{.Fortran} and
@code{.External}, R must locate the specified native routine by looking
in the appropriate shared library/DLL.  By default, R uses the operating
system-specific dynamic loader to lookup the symbol.  Alternatively, the
author of the DLL can explicitly register routines with R and use a
single, platform-independent mechanism for finding the routines in the
DLL.  One can use this registration mechanism to provide additional
information about a routine, including the number and type of the
arguments, and also make it available to S programmers under a different
name.  In the future, registration may be used to implement a form of
``secure'' or limited native access.

To register routines with R, one calls the C routine
@code{R_registerRoutines}.  This is typically done when the DLL is first
loaded within the initialization routine @code{R_init_@var{dll name}}
described in @ref{dyn.load and dyn.unload}.  @code{R_registerRoutines}
takes 5 arguments.  The first is the @code{DllInfo} object passed by R
to the initialization routine. This is where R stores the information
about the methods.  The remaining 4 arguments are arrays describing the
routines for each of the 4 different interfaces: @code{.C},
@code{.Call}, @code{.Fortran} and @code{.External}.  Each argument is a
@code{NULL}-terminated array of the element types given in the following
table:

@quotation
@multitable {@code{.External  }} {@code{R_ExternalMethodDef}}

@item @code{.C} @tab @code{R_CMethodDef}
@item @code{.Call} @tab @code{R_CallMethodDef}
@item @code{.Fortran} @tab @code{R_FortranMethodDef}
@item @code{.External} @tab @code{R_ExternalMethodDef}

@end multitable
@end quotation

Currently, the @code{R_ExternalMethodDef} is the same as
@code{R_CallMethodDef} type and contains fields for the name of the
routine by which it can be accessed in R, a pointer to the actual native
symbol (i.e., the routine itself), and the number of arguments the
routine expects.  For routines with a variable number of arguments
invoked via the @code{.External} interface, one specifies @math{-1} for
the number of arguments which tells R not to check the actual number
passed.  For example, if we had a routine named @code{myCall} defined as

@smallexample
SEXP myCall(SEXP a, SEXP b, SEXP c);
@end smallexample

@noindent
we would describe this as

@smallexample
R_CallMethodDef callMethods[]  = @{
  @{"myCall",  &myCall, 3@},
  @{NULL, NULL, 0@}
@};
@end smallexample

@noindent
along with any other routines for the @code{.Call} interface.

Routines for use with the @code{.C} and @code{.Fortran} interfaces are
described with similar data structures, but which have two additional
fields for describing the type and ``style'' of each argument.  Each
of these can be omitted. However, if specified, each should be an
array with the same number of elements as the number of parameters for
the routine.  The types array should contain the @code{SEXP} types
describing the expected type of the argument. (Technically, the
elements of the types array are of type
@code{R_NativePrimitiveArgType} which is just an unsigned integer.)
The S types and corresponding type identifiers are provided in the
following table:

@quotation
@multitable {@code{character  }} {@code{SINGLESXP}}

@item @code{numeric} @tab @code{REALSXP}
@item @code{integer} @tab @code{INTSXP}
@item @code{logical} @tab @code{LGLSXP}
@item @code{single} @tab @code{SINGLESXP}
@item @code{character} @tab @code{STRSXP}
@item @code{list} @tab @code{VECSXP}

@end multitable
@end quotation

Consider a C routine, @code{myC}, declared as

@smallexample
void myC(double *x, int *n, char **names, int *status);
@end smallexample

We would register it as

@smallexample
R_CMethodDef cMethods[] = @{
   @{"myC", &myC, 4, @{REALSXP, INTSXP, STRSXP, LGLSXP@}@},
   @{NULL, NULL, 0@}
@};
@end smallexample

One can also specify whether each argument is used simply as input, or
as output, or as both input and output.  The style field in the
description of a method is used for this.  The purpose is to allow R to
more efficiently transfer values across the S-C/Fortran interface by
avoiding copying values when it is not necessary. Typically, one omits
this information in the registration data.

Having created the arrays describing each routine, the last step is to
actually register them with R.  We do this by calling
@code{R_registerRoutines}.  For example, if we have the descriptions
above for the routines accessed by the @code{.C} and @code{.Call}
we would use the following code:

@smallexample
void
R_init_myLib(DllInfo *info)
@{
   R_registerRoutines(info, cMethods, callMethods, NULL, NULL);
@}
@end smallexample

This routine will be invoked when R loads the shared library/DLL named
@code{myLib}.  The last two arguments in the call to
@code{R_registerRoutines} are for the routines accessed by
@code{.Fortran} and @code{.External} interfaces.  In our example, these
are given as @code{NULL} since we don't have any routines of these
types.

When R unloads a shared library/DLL, any registered routines are
automatically removed. There is no (direct) facility for unregistering
a symbol.


Examples of registering routines can be found in the different packages
in the R source tree (e.g., @pkg{mva}, @pkg{ctest}, @pkg{lqs}).  Also,
there is a brief, high-level introduction in @emph{R News} (volume 1/3,
September 2001, pages 20-23).

Additionally, there are (experimental) tools that can be used to
automate the generation of the code to register the routines for a
collection of C files. See the @code{GccTranslationUnit} module on the
Omegahat Web site at @uref{http://www.omegahat.org/GccTranslationUnit/}
for more information.


@node Creating shared libraries, Interfacing C++ code, Registering native routines, System and foreign language interfaces
@section Creating shared libraries
@cindex Creating shared libraries
@findex R CMD SHLIB

Under Unix, shared libraries for loading into @R{} can be created using
@code{R CMD SHLIB}.  This accepts as arguments a list of files which
must be object files (with extension @file{.o}) or C, C++, or FORTRAN
sources (with extensions @file{.c}, @file{.cc} or @file{.cpp} or
@file{.C}, and @file{.f}, respectively).  See @kbd{R CMD SHLIB --help},
or the on-line help for @code{SHLIB}, for usage information.  If
compiling the source files does not work ``out of the box'', you can
specify additional flags by setting some of the variables
@vindex PKG_CPPFLAGS
@code{PKG_CPPFLAGS} (for the C preprocessor, typically @samp{-I} flags),
@vindex PKG_CFLAGS
@vindex PKG_CXXFLAGS
@vindex PKG_FFLAGS
@code{PKG_CFLAGS}, @code{PKG_CXXFLAGS}, and @code{PKG_FFLAGS} (for the
C, C++, and FORTRAN compilers, respectively) in the file @file{Makevars}
in the compilation directory, or write a @file{Makefile} in the
compilation directory containing the rules required (or, of course,
create the object files directly from the command line).
@vindex PKG_LIBS
Similarly, variable @code{PKG_LIBS} in @file{Makevars} can be used for
additional @samp{-l} and @samp{-L} flags to be passed to the linker when
building the shared library.

If an add-on package @var{pkg} contains C, C++, or FORTRAN code in its
@file{src} subdirectory, @code{R CMD INSTALL} creates a shared library
(for loading into @R{} in the @code{.First.lib} function of the package)
either automatically using the above @code{R CMD SHLIB} mechanism, or
using Make if directory @file{src} contains a @file{Makefile}.  In both
cases, if file @file{Makevars} exists it is read first when invoking
@code{make}.  If a @file{Makefile} is really needed or provided, it
needs to ensure that the shared library created is linked against all
FORTRAN 77 intrinsic and run-time libraries that @R{} was linked
against; Make variable @code{FLIBS} contains this information.

The Windows equivalent is the command @code{Rcmd SHLIB}; files
@file{Makevars.win} or @file{Makefile.win} are used in preference to
@file{Makevars} or @file{Makefile} if they exist.  (This does need the
files in the @R{} binary Windows distribution for installing source
packages to be installed.)  For details of building DLLs with
a variety of compilers, see @samp{readme.packages}.

@node Interfacing C++ code, Handling R objects in C, Creating shared libraries, System and foreign language interfaces
@section Interfacing C++ code
@cindex Interfacing C++ code
@cindex C++ code, interfacing

Suppose we have the following hypothetical C++ library, consisting of
the two files @file{X.hh} and @file{X.cc}, and implementing the two
classes @code{X} and @code{Y} which we want to use in @R{}.

@cartouche
@smallexample
// X.hh

class X @{
public: X (); ~X ();
@};

class Y @{
public: Y (); ~Y ();
@};
@end smallexample
@end cartouche

@cartouche
@smallexample
// X.cc

#include <iostream.h>
#include "X.hh"

static Y y;

X::X()  @{ cout << "constructor X" << endl; @}
X::~X() @{ cout << "destructor X" << endl; @}
Y::Y()  @{ cout << "constructor Y" << endl; @}
Y::~Y() @{ cout << "destructor Y" << endl; @}
@end smallexample
@end cartouche

To use with @R{}, the only thing we have to do is writing a wrapper
function and ensuring that the function is enclosed in

@smallexample
@group
extern "C" @{

@}
@end group
@end smallexample

For example,

@cartouche
@smallexample
// X_main.cc:

#include "X.hh"

extern "C" @{

void X_main () @{
  X x;
@}

@} // extern "C"
@end smallexample
@end cartouche

Compiling and linking should be done with the C++ compiler-linker
(rather than the C compiler-linker or the linker itself); otherwise, the
C++ initialization code (and hence the constructor of the static
variable @code{Y}) are not called.  On a properly configured Unix system
(support for C++ was added in @R{} version 1.1), one can simply use

@smallexample
R CMD SHLIB X.cc X_main.cc
@end smallexample

@noindent
to create the shared library, typically @file{X.so} (the file name
extension may be different on your platform).  Now starting R yields

@smallexample
@group
R : Copyright 2000, The R Development Core Team
Version 1.1.0 Under development (unstable) (April 14, 2000)
...
Type    "q()" to quit R.
@end group

@group
R> dyn.load(paste("X", .Platform$dynlib.ext, sep = ""))
constructor Y
R> .C("X_main")
constructor X
destructor X
list()
R> q()
Save workspace image? [y/n/c]: y
destructor Y
@end group
@end smallexample

The R for Windows @acronym{FAQ} (@file{rw-FAQ}) contains details of how
to compile this example under various Windows compilers.

Using C++ iostreams, as in this example, is best avoided.  There is no
guarantee that the output will appear in the R console, and indeed it
will not on the R for Windows console.  Use R code or the C entry points
(@pxref{Printing}) for all I/O if at all possible.


@node Handling R objects in C, Interface functions .Call and .External, Interfacing C++ code, System and foreign language interfaces
@section Handling R objects in C
@cindex Handling R objects in C

Using C code to speed up the execution of an @R{} function is often very
fruitful.  Traditionally this has been done via the @code{.C} function
in @R{}.
@c (for details, see the @R{} documentation on @code{.C}).
One restriction of this interface is that the @R{} objects can not be
handled directly in C.  This becomes more troublesome when one wishes to
call @R{} functions from within the C code.  There is a C function
provided called @code{call_R} (also known as @code{call_S} for
compatibility with S) that can do that, but it is cumbersome to use, and
the mechanisms documented here are usually simpler to use, as well as
more powerful.

If a user really wants to write C code using internal @R{} data
structures, then that can be done using the @code{.Call} and
@code{.External} function.  The syntax for the calling function in @R{}
in each case is similar to that of @code{.C}, but the two functions have
rather different C interfaces.  Generally the @code{.Call} interface
(which is modelled on the interface of the same name in @Sl{} version 4)
is a little simpler to use, but @code{.External} is a little more
general.
@findex .Call
@findex .External

A call to @code{.Call} is very similar to @code{.C}, for example

@smallexample
.Call("convolve2", a, b)
@end smallexample

@noindent
The first argument should be a character string giving a C symbol name
of code that has already been loaded into @R{}.  Up to 65 @R{} objects
can passed as arguments.  The C side of the interface is

@smallexample
@group
#include <R.h>
#include <Rinternals.h>

SEXP convolve2(SEXP a, SEXP b)
 ...
@end group
@end smallexample

A call to @code{.External} is almost identical

@smallexample
.External("convolveE", a, b)
@end smallexample

@noindent
but the C side of the interface is different, having only one argument

@smallexample
@group
#include <R.h>
#include <Rinternals.h>

SEXP convolveE(SEXP args)
 ...
@end group
@end smallexample

@noindent
Here @code{args} is a @code{LISTSXP}, a Lisp-style list from which the
arguments can be extracted.

In each case the @R{} objects are available for manipulation via a set
of functions and macros defined in the header file @file{Rinternals.h}
or some higher-level macros defined in @file{Rdefines.h}.  See
@ref{Interface functions .Call and .External} for details on
@code{.Call} and @code{.External}.

Before you decide to use @code{.Call} or @code{.External}, you should
look at other alternatives.  First, consider working in interpreted @R{}
code; if this is fast enough, this is normally the best option.  You
should also see if using @code{.C} is enough.  If the task to be
performed in C is simple enough requiring no call to @R{}, @code{.C}
suffices.  The new interfaces are recent additions to @Sl{} and @R{},
and a great deal of useful code has been written using just @code{.C}
before they were available.  The @code{.Call} and @code{.External}
interfaces allow much more control, but they also impose much greater
responsibilities so need to be used with care.  Neither @code{.Call} nor
@code{.External} copy their arguments.  You should treat arguments you
receive through these interfaces as read-only.

There are two approaches that can be taken to handling @R{} objects from
within C code.  The first (historically) is to use the macros and
functions that have been used to implement the core parts of @R{}
through @code{.Internal} calls.  A public subset of these is defined in
the header file @file{Rinternals.h} in the directory
@file{@var{R_HOME}/include} that should be available on any @R{}
installation.

A more recent approach is to use @R{} versions of the macros and
functions defined for the @Sl{} version 4 interface @code{.Call}, which
are defined in the header file @file{Rdefines.h}.  This is a somewhat
simpler approach, and is certainly to be preferred if the code might be
shared with @Sl{} at any stage.

A substantial amount of @R{} is implemented using the functions and
macros described here, so the @R{} source code provides a rich source of
examples and ``how to do it'': indeed many of the examples here were
developed by examining closely @R{} system functions for similar tasks.
Do make use of the source code for inspirational examples.

It is necessary to know something about how @R{} objects are handled in
C code.  All the @R{} objects you will deal with will be handled with
the type @dfn{SEXP}@footnote{SEXP is an acronym for @emph{S}imple
@emph{EXP}ression, common in LISP-like language syntaxes.}, which is a
pointer to a structure with typedef @code{SEXPREC}.  Think of this
structure as a @emph{variant type} that can handle all the usual types
of @R{} objects, that is vectors of various modes, functions,
environments, language objects and so on.  The details are given later
in this section, but for most purposes the programmer does not need to
know them.  Think rather of a model such as that used by Visual Basic,
in which @R{} objects are handed around in C code (as they are in
interpreted @R{} code) as the variant type, and the appropriate part is
extracted for, for example, numerical calculations, only when it is
needed.  As in interpreted @R{} code, much use is made of coercion to
force the variant object to the right type.

@menu
* Garbage Collection::
* Allocating storage::
* Details of R types::
* Attributes::
* Classes::
* Handling lists::
* Finding and setting variables::
@end menu

@node Garbage Collection, Allocating storage, Handling R objects in C, Handling R objects in C
@subsection Handling the effects of garbage collection
@cindex Garbage collection

@findex PROTECT
@findex UNPROTECT

We need to know a little about the way @R{} handles memory allocation.
The memory allocated for @R{} objects is not freed by the user; instead,
the memory is from time to time @dfn{garbage collected}.  That is, some
or all of the allocated memory not being used is freed.  (Prior to @R{}
1.2, objects could be moved, too.)

The @R{} object types are represented by a C structure defined by a
typedef @code{SEXPREC} in @file{Rinternals.h}.  It contains several
things among which are pointers to data blocks and to other
@code{SEXPREC}s.  A @code{SEXP} is simply a pointer to a @code{SEXPREC}.

If you create an @R{} object in your C code, you must tell @R{} that you
are using the object by using the @code{PROTECT} macro on a pointer to
the object. This tells @R{} that the object is in use so it is not
destroyed.  Notice that it is the object which is protected, not the
pointer variable.  It is a common mistake to believe that if you invoked
@code{PROTECT(@var{p})} at some point then @var{p} is protected from
then on, but that is not true once a new object is assigned to @var{p}.

Protecting an R object automatically protects all the @R{} objects
pointed to in the corresponding @code{SEXPREC}.

The programmer is solely responsible for housekeeping the calls to
@code{PROTECT}.  There is a corresponding macro @code{UNPROTECT} that
takes as argument an @code{int} giving the number of objects to
unprotect when they are no longer needed.  The protection mechanism is
stack-based, so @code{UNPROTECT(@var{n})} unprotects the last @var{n}
objects which were protected.  The calls to @code{PROTECT} and
@code{UNPROTECT} must balance when the user's code returns.  @R{} will
warn about @code{"stack imbalance in .Call"} (or @code{.External}) if
the housekeeping is wrong.

Here is a small example of creating an @R{} numeric vector in C code.
First we use the macros in @file{Rdefines.h}:

@smallexample
@group
#include <R.h>
#include <Rdefines.h>

  SEXP ab;
    ....
  PROTECT(ab = NEW_NUMERIC(2));
  NUMERIC_POINTER(ab)[0] = 123.45;
  NUMERIC_POINTER(ab)[1] = 67.89;
  UNPROTECT(1);
@end group
@end smallexample

@noindent
and then those in @file{Rinternals.h}:

@smallexample
@group
#include <R.h>
#include <Rinternals.h>

  SEXP ab;
    ....
  PROTECT(ab = allocVector(REALSXP, 2));
  REAL(ab)[0] = 123.45;
  REAL(ab)[1] = 67.89;
  UNPROTECT(1);
@end group
@end smallexample

Now, the reader may ask how the @R{} object could possibly get removed
during those manipulations, as it is just our C code that is running. As
it happens, we can do without the protection in this example, but in
general we do not know (nor want to know) what is hiding behind the @R{}
macros and functions we use, and any of them might cause memory to be
allocated, hence garbage collection and hence our object @code{ab} to be
removed. It is usually wise to err on the side of caution and assume
that any of the @R{} macros and functions might remove the object.

In some cases it is necessary to keep better track of whether protection
is really needed. Be particularly aware of situations where a large
number of objects are generated. The pointer protection stack has a
fixed size (default 10,000) and can become full. It is not a good idea
then to just @code{PROTECT} everything in sight and @code{UNPROTECT}
several thousand objects at the end. It will almost invariably be
possible to either assign the objects as part of another object (which
automatically protects them) or unprotect them immediately after use.

Protection is not needed for objects which @R{} already knows are in
use.  In particular, this applies to function arguments.

There is a less-used macro @code{UNPROTECT_PTR(@var{s})} that unprotects
the object pointed to by the @code{SEXP} @var{s}, even if it is not the
top item on the pointer protection stack. This is rarely needed outside
the parser (the R sources have one example, in
@file{src/main/plot3d.c}).
@findex UNPROTECT_PTR

@node Allocating storage, Details of R types, Garbage Collection, Handling R objects in C
@subsection Allocating storage
@cindex Allocating storage

For many purposes it is sufficient to allocate @R{} objects and
manipulate those.  There are quite a few @code{alloc@var{Xxx}} functions
defined in @file{Rinternals.h}---you may want to explore them.  These
allocate @R{} objects of various types, and for the standard vector
types there are @code{NEW_@var{XXX}} macros defined in
@file{Rdefines.h}.

If storage is required for C objects during the calculations this is
best allocating by calling @code{R_alloc}; @pxref{Memory allocation}.
All of these memory allocation routines do their own error-checking, so
the programmer may assume that they will raise an error and not return
if the memory cannot be allocated.

@node Details of R types, Attributes, Allocating storage, Handling R objects in C
@subsection Details of R types
@cindex Details of R types

Users of the @file{Rinternals.h} macros will need to know how the @R{}
types are known internally: this is more or less completely hidden if
the @file{Rdefines.h} macros are used.

The different @R{} data types are represented in C by @dfn{SEXPTYPE}.
Some of these are familiar from @R{} and some are internal data types.
The usual @R{} object modes are given in the table.

@quotation
@multitable {SEXPTYPE} {numeric with storage mode integer integer}

@item SEXPTYPE @tab @R{} equivalent

@item @code{REALSXP}  @tab numeric with storage mode @code{double}
@item @code{INTSXP}   @tab integer
@item @code{CPLXSXP}  @tab complex
@item @code{LGLSXP}   @tab logical
@item @code{STRSXP}   @tab character
@item @code{VECSXP}   @tab list (generic vector)
@item @code{LISTSXP}  @tab ``dotted-pair'' list
@item @code{DOTSXP}   @tab a @samp{@dots{}} object
@item @code{NILSXP}   @tab NULL
@item @code{SYMSXP}   @tab name/symbol
@item @code{CLOSXP}   @tab function or function closure
@item @code{ENVSXP}   @tab environment

@end multitable
@end quotation

@noindent
Among the important internal @code{SEXPTYPE}s are @code{LANGSXP},
@code{CHARSXP} etc.  (@strong{Note:} although it is possible to return
objects of internal types, it is unsafe to do so as assumptions are
made about how they are handled which may be violated at user-level
evaluation.)

Unless you are very sure about the type of the arguments, the code
should check the data types.  Sometimes it may also be necessary to
check data types of objects created by evaluating an @R{} expression in
the C code.  You can use functions like @code{isReal}, @code{isInteger}
and @code{isString} to do type checking.  See the header file
@file{Rinternals.h} for definitions of other such functions.  All of
these take a @code{SEXP} as argument and return 1 or 0 to indicate
@var{TRUE} or @var{FALSE}.  Once again there are two ways to do this,
and @file{Rdefines.h} has macros such as @code{IS_NUMERIC}.

What happens if the @code{SEXP} is not of the correct type? Sometimes
you have no other option except to generate an error.  You can use the
function @code{error} for this.  It is usually better to coerce the
object to the correct type.  For example, if you find that an
@code{SEXP} is of the type @code{INTEGER}, but you need a @code{REAL}
object, you can change the type by using, equivalently,

@smallexample
PROTECT(@var{newSexp} = coerceVector(@var{oldSexp}, REALSXP));
@end smallexample

@noindent
or

@smallexample
PROTECT(@var{newSexp} = AS_NUMERIC(@var{oldSexp}));
@end smallexample

@noindent
Protection is needed as a new @emph{object} is created; the object
formerly pointed to by the @code{SEXP} is still protected but now
unused.

All the coercion functions do their own error-checking, and generate
@code{NA}s with a warning or stop with an error as appropriate.

So far we have only seen how to create and coerce @R{} objects from C
code, and how to extract the numeric data from numeric @R{} vectors.
These can suffice to take us a long way in interfacing @R{} objects to
numerical algorithms, but we may need to know a little more to create
useful return objects.

@node Attributes, Classes, Details of R types, Handling R objects in C
@subsection Attributes
@cindex Attributes

Many @R{} objects have attributes: some of the most useful are classes
and the @code{dim} and @code{dimnames} that mark objects as matrices or
arrays.  It can also be helpful to work with the @code{names} attribute
of vectors.

To illustrate this, let us write code to take the outer product of two
vectors (which @code{outer} and @code{%o%} already do).  As usual the
@R{} code is simple

@smallexample
out <- function(x, y) .Call("out", as.double(x), as.double(y))
@end smallexample

@noindent
where we expect @code{x} and @code{y} to be numeric vectors, possibly
with names.  This time we do the coercion in the calling @R{} code.

C code to do the computations is

@smallexample
@group
#include <R.h>
#include <Rinternals.h>

SEXP out(SEXP x, SEXP y)
@{
  int i, j, nx, ny;
  double tmp;
  SEXP ans;

  nx = length(x); ny = length(y);
  PROTECT(ans = allocMatrix(REALSXP, nx, ny));
  for(i = 0; i < nx; i++) @{
    tmp = REAL(x)[i];
    for(j = 0; j < ny; j++)
      REAL(ans)[i + nx*j] = tmp * REAL(y)[j];
  @}
  UNPROTECT(1);
  return(ans);
@}
@end group
@end smallexample

@noindent
but we would like to set the @code{dimnames} of the result.  Although
@code{allocMatrix} provides a short cut, we will show how to set the
@code{dim} attribute directly.

@smallexample
#include <R.h>
#include <Rinternals.h>

@group
SEXP out(SEXP x, SEXP y)
@{
  int i, j, nx, ny;
  double tmp;
  SEXP ans, dim, dimnames;
@end group

@group
  nx = length(x); ny = length(y);
  PROTECT(ans = allocVector(REALSXP, nx*ny));
  for(i = 0; i < nx; i++) @{
    tmp = REAL(x)[i];
    for(j = 0; j < ny; j++)
      REAL(ans)[i + nx*j] = tmp * REAL(y)[j];
  @}
@end group

@group
  PROTECT(dim = allocVector(INTSXP, 2));
  INTEGER(dim)[0] = nx; INTEGER(dim)[1] = ny;
  setAttrib(ans, R_DimSymbol, dim);
@end group

@group
  PROTECT(dimnames = allocVector(VECSXP, 2));
  SET_VECTOR_ELT(dimnames, 0, getAttrib(x, R_NamesSymbol));
  SET_VECTOR_ELT(dimnames, 1, getAttrib(y, R_NamesSymbol));
  setAttrib(ans, R_DimNamesSymbol, dimnames);
@end group

@group
  UNPROTECT(3);
  return(ans);
@}
@end group
@end smallexample

This example introduces several new features.  The @code{getAttrib} and
@code{setAttrib}
@findex getAttrib
@findex setAttrib
functions get and set individual attributes.  Their second argument is a
@code{SEXP} defining the name in the symbol table of the attribute we
want; these and many such symbols are defined in the header file
@file{Rinternals.h}.

There are shortcuts here too: the functions @code{namesgets},
@code{dimgets} and @code{dimnamesgets} are the internal versions of
@code{names<-}, @code{dim<-} and @code{dimnames<-}, and there are
functions such as @code{GetMatrixDimnames} and @code{GetArrayDimnames}.

What happens if we want to add an attribute that is not pre-defined? We
need to add a symbol for it @emph{via} a call to
@findex install
@code{install}.  Suppose for illustration we wanted to add an attribute
@code{"version"} with value @code{3.0}.  We could use

@smallexample
@group
  SEXP version;
  PROTECT(version = allocVector(REALSXP, 1));
  REAL(version) = 3.0;
  setAttrib(ans, install("version"), version);
  UNPROTECT(1);
@end group
@end smallexample

Using @code{install} when it is not needed is harmless and provides a
simple way to retrieve the symbol from the symbol table if it is already
installed.

@node Classes, Handling lists, Attributes, Handling R objects in C
@subsection Classes
@cindex Classes

In @R{} the class is just the attribute named @code{"class"} so it can
be handled as such, but there is a shortcut @code{classgets}.  Suppose
we want to give the return value in our example the class @code{"mat"}.
We can use

@smallexample
@group
#include <R.h>
#include <Rdefines.h>
    ....
  SEXP ans, dim, dimnames, class;
    ....
  PROTECT(class = allocVector(STRSXP, 1));
  SET_STRING_ELT(class, 0, mkChar("mat"));
  classgets(ans, class);
  UNPROTECT(4);
  return(ans);
@}
@end group
@end smallexample

@noindent
As the value is a character vector, we have to know how to create that
from a C character array, which we do using the function
@code{mkChar}.

@node Handling lists, Finding and setting variables, Classes, Handling R objects in C
@subsection Handling lists
@cindex Handling lists

Some care is needed with lists, as @R{} has moved from using LISP-like
lists (now called ``pairlists'') to S-like generic vectors.  As a
result, the appropriate test for an object of mode @code{list} is
@code{isNewList}, and we need @code{allocVector(VECSXP, @var{n}}) and
@emph{not} @code{allocList(@var{n})}.

List elements can be retrieved or set by direct access to the elements
of the generic vector.  Suppose we have a list object

@smallexample
a <- list(f=1, g=2, h=3)
@end smallexample

@noindent
Then we can access @code{a$g} as @code{a[[2]]} by

@smallexample
@group
  double g;
    ....
  g = REAL(VECTOR_ELT(a, 1))[0];
@end group
@end smallexample

This can rapidly become tedious, and the following function (based on
one in package @pkg{nls}) is very useful:

@smallexample
@group
/* get the list element named str, or return NULL */

SEXP getListElement(SEXP list, char *str)
@{
  SEXP elmt = R_NilValue, names = getAttrib(list, R_NamesSymbol);
  int i;
@end group

@group
  for (i = 0; i < length(list); i++)
    if(strcmp(CHAR(STRING_ELT(names, i)), str) == 0) @{
      elmt = VECTOR_ELT(list, i);
      break;
    @}
  return elmt;
@}
@end group
@end smallexample

@noindent
and enables us to say

@smallexample
@group
  double g;
  g = REAL(getListElement(a, "g"))[0];
@end group
@end smallexample

@node Finding and setting variables,  , Handling lists, Handling R objects in C
@subsection Finding and setting variables
@cindex Finding variables
@cindex Setting variables

It will be usual that all the @R{} objects needed in our C computations
are passed as arguments to @code{.Call} or @code{.External}, but it is
possible to find the values of @R{} objects from within the C given
their names.  The following code is the equivalent of @code{get(name,
envir = rho)}.

@smallexample
@group
SEXP getvar(SEXP name, SEXP rho)
@{
  SEXP ans;

  if(!isString(name) || length(name) != 1)
    error("name is not a single string");
  if(!isEnvironment(rho))
    error("rho should be an environment");
  ans = findVar(install(CHAR(STRING_ELT(name, 0))), rho);
  printf("first value is %f\n", REAL(ans)[0]);
  return(R_NilValue);
@}
@end group
@end smallexample

The main work is done by
@findex findVar
@code{findVar}, but to use it we need to install @code{name} as a name
in the symbol table.  As we wanted the value for internal use, we return
@code{NULL}.

Similar functions with syntax

@smallexample
@group
void defineVar(SEXP symbol, SEXP value, SEXP rho)
void setVar(SEXP symbol, SEXP value, SEXP rho)
@end group
@end smallexample
@findex defineVar
@findex setVar

@noindent
can be used to assign values to @R{} variables.  @code{defineVar}
creates a new binding or changes the value of an existing binding in the
specified environment frame; it is the analogue of @code{assign(symbol,
value, envir = rho, inherits = FALSE)}, but unlike @code{assign},
@code{defineVar} does not make a copy of the object
@code{value}.@footnote{You can assign a @emph{copy} of the object in the
environment frame @code{rho} using @code{defineVar(symbol,
duplicate(value), rho)}).}  @code{setVar} searches for an existing
binding for @code{symbol} in @code{rho} or its enclosing environments.
If a binding is found, its value is changed to @code{value}.  Otherwise,
a new binding with the specified value is created in the global
environment.  This corresponds to @code{assign(symbol, value, envir =
rho, inherits = TRUE)}.


@node Interface functions .Call and .External, Evaluating R expressions from C, Handling R objects in C, System and foreign language interfaces
@section Interface functions @code{.Call} and @code{.External}
@cindex Interfaces to compiled code

In this section we consider the details of the @R{}/C interfaces.

These two interfaces have almost the same functionality. @code{.Call} is
based on the interface of the same name in @Sl{} version 4, and
@code{.External} is based on @code{.Internal}.  @code{.External} is more
complex but allows a variable number of arguments.

@menu
* Calling .Call::
* Calling .External::
* Missing and special values::
@end menu

@node Calling .Call, Calling .External, Interface functions .Call and .External, Interface functions .Call and .External
@subsection Calling @code{.Call}

@findex .Call

Let us convert our finite convolution example to use @code{.Call}, first
using the @file{Rdefines.h} macros.  The calling function in @R{} is

@smallexample
conv <- function(a, b) .Call("convolve2", a, b)
@end smallexample

@noindent
which could hardly be simpler, but as we shall see all the type checking
must be transferred to the C code, which is

@smallexample
@group
#include <R.h>
#include <Rdefines.h>

SEXP convolve2(SEXP a, SEXP b)
@{
  int i, j, na, nb, nab;
  double *xa, *xb, *xab;
  SEXP ab;

  PROTECT(a = AS_NUMERIC(a));
  PROTECT(b = AS_NUMERIC(b));
  na = LENGTH(a); nb = LENGTH(b); nab = na + nb - 1;
  PROTECT(ab = NEW_NUMERIC(nab));
  xa = NUMERIC_POINTER(a); xb = NUMERIC_POINTER(b);
  xab = NUMERIC_POINTER(ab);
  for(i = 0; i < nab; i++) xab[i] = 0.0;
  for(i = 0; i < na; i++)
    for(j = 0; j < nb; j++) xab[i + j] += xa[i] * xb[j];
  UNPROTECT(3);
  return(ab);
@}
@end group
@end smallexample

Note that unlike the macros in @Sl{} version 4, the @R{} versions of
these macros do check that coercion can be done and raise an error if it
fails.  They will raise warnings if missing values are introduced by
coercion.  Although we illustrate doing the coercion in the C code here,
it often is simpler to do the necessary coercions in the @R{} code.

Now for the version in @R{}-internal style.  Only the C code changes.

@smallexample
@group
#include <R.h>
#include <Rinternals.h>

SEXP convolve2(SEXP a, SEXP b)
@{
  int i, j, na, nb, nab;
  double *xa, *xb, *xab;
  SEXP ab;

  PROTECT(a = coerceVector(a, REALSXP));
  PROTECT(b = coerceVector(b, REALSXP));
  na = length(a); nb = length(b); nab = na + nb - 1;
  PROTECT(ab = allocVector(REALSXP, nab));
  xa = REAL(a); xb = REAL(b);
  xab = REAL(ab);
  for(i = 0; i < nab; i++) xab[i] = 0.0;
  for(i = 0; i < na; i++)
    for(j = 0; j < nb; j++) xab[i + j] += xa[i] * xb[j];
  UNPROTECT(3);
  return(ab);
@}
@end group
@end smallexample

@noindent
This is called in exactly the same way.

@node Calling .External, Missing and special values, Calling .Call, Interface functions .Call and .External
@subsection Calling @code{.External}

@findex .External

We can use the same example to illustrate @code{.External}.  The @R{}
code changes only by replacing @code{.Call} by @code{.External}

@smallexample
conv <- function(a, b) .External("convolveE", a, b)
@end smallexample

@noindent
but the main change is how the arguments are passed to the C code, this
time as a single SEXP.  The only change to the C code is how we handle
the arguments.

@smallexample
@group
#include <R.h>
#include <Rinternals.h>

SEXP convolveE(SEXP args)
@{
  int i, j, na, nb, nab;
  double *xa, *xb, *xab;
  SEXP a, b, ab;

  PROTECT(a = coerceVector(CADR(args), REALSXP));
  PROTECT(b = coerceVector(CADDR(args), REALSXP));
    ...
@}
@end group
@end smallexample

@noindent
Once again we do not need to protect the arguments, as in the @R{} side
of the interface they are objects that are already in use.  The macros

@smallexample
@group
  first = CADR(args);
  second = CADDR(args);
  third = CADDDR(args);
  fourth = CAD4R(args);
@end group
@end smallexample

@noindent
provide convenient ways to access the first four arguments.  More
generally we can use the
@findex CAR
@findex CDR
@code{CDR} and @code{CAR} macros as in

@smallexample
@group
  args = CDR(args); a = CAR(args);
  args = CDR(args); b = CAR(args);
@end group
@end smallexample

@noindent
which clearly allows us to extract an unlimited number of arguments
(whereas @code{.Call} has a limit, albeit at 65 not a small one).

More usefully, the @code{.External} interface provides an easy way to
handle calls with a variable number of arguments, as @code{length(args)}
will give the number of arguments supplied (of which the first is
ignored).  We may need to know the names (`tags') given to the actual
arguments, which we can by using the @code{TAG} macro and using
something like the following example, that prints the names and the first
value of its arguments if they are vector types.

@smallexample
@group
#include <R_ext/PrtUtil.h>

SEXP showArgs(SEXP args)
@{
  int i, nargs;
  Rcomplex cpl;
  char *name;
@end group

@group
  if((nargs = length(args) - 1) > 0) @{
    for(i = 0; i < nargs; i++) @{
      args = CDR(args);
      name = CHAR(PRINTNAME(TAG(args)));
      switch(TYPEOF(CAR(args))) @{
      case REALSXP:
        Rprintf("[%d] '%s' %f\n", i+1, name, REAL(CAR(args))[0]);
        break;
@end group
@group
      case LGLSXP:
      case INTSXP:
        Rprintf("[%d] '%s' %d\n", i+1, name, INTEGER(CAR(args))[0]);
        break;
@end group
@group
      case CPLXSXP:
        cpl = COMPLEX(CAR(args))[0];
        Rprintf("[%d] '%s' %f + %fi\n", i+1, name, cpl.r, cpl.i);
        break;
@end group
@group
      case STRSXP:
        Rprintf("[%d] '%s' %s\n", i+1, name,
               CHAR(STRING_ELT(CAR(args), 0)));
        break;
@end group
@group
      default:
        Rprintf("[%d] '%s' R type\n", i+1, name);
      @}
    @}
  @}
  return(R_NilValue);
@}
@end group
@end smallexample

This can be called by the wrapper function

@smallexample
showArgs <- function(...) .External("showArgs", ...)
@end smallexample

@noindent
Note that this style of programming is convenient but not necessary, as
an alternative style is

@smallexample
showArgs <- function(...) .Call("showArgs1", list(...))
@end smallexample

@node Missing and special values,  , Calling .External, Interface functions .Call and .External
@subsection Missing and special values
@cindex Missing values
@cindex IEEE special values

One piece of error-checking the @code{.C} call does (unless @code{NAOK}
is true) is to check for missing (@code{NA}) and @acronym{IEEE} special
values (@code{Inf}, @code{-Inf} and @code{NaN}) and give an error if any
are found.  With the @code{.Call} interface these will be passed to our
code.  In this example the special values are no problem, as
@acronym{IEEE} arithmetic will handle them correctly.  In the current
implementation this is also true of @code{NA} as it is a type of
@code{NaN}, but it is unwise to rely on such details.  Thus we will
re-write the code to handle @code{NA}s using macros defined in
@file{Arith.h} included by @file{R.h}.

The code changes are the same in any of the versions of @code{convolve2}
or @code{convolveE}:

@smallexample
@group
    ...
  for(i = 0; i < na; i++)
    for(j = 0; j < nb; j++)
        if(ISNA(xa[i]) || ISNA(xb[j]) || ISNA(xab[i + j]))
          xab[i + j] = NA_REAL;
        else
          xab[i + j] += xa[i] * xb[j];
    ...
@end group
@end smallexample

@findex ISNA
@findex ISNAN

Note that the @code{ISNA} macro, and the similar macros @code{ISNAN}
(which checks for @code{NaN} or @code{NA}) and @code{R_FINITE} (which is
false for @code{NA} and all the special values), only apply to numeric
values of type @code{double}.  Missingness of integers, logicals and
character strings can be tested by equality to the constants
@code{NA_INTEGER}, @code{NA_LOGICAL} and @code{NA_STRING}.  These and
@code{NA_REAL} can be used to set elements of @R{} vectors to @code{NA}.

The constants @code{R_NaN}, @code{R_PosInf}, @code{R_NegInf} and
@code{R_NaReal} can be used to set @code{double}s to the special values.

@node Evaluating R expressions from C, Debugging, Interface functions .Call and .External, System and foreign language interfaces
@section Evaluating R expressions from C
@cindex Evaluating R expressions from C

We noted that the @code{call_R} interface could be used to evaluate @R{}
expressions from C code, but the current interfaces are much more
convenient to use.  The main function we will use is

@smallexample
SEXP eval(SEXP expr, SEXP rho);
@end smallexample

@noindent
the equivalent of the interpreted @R{} code @code{eval(expr, envir =
rho)}, although we can also make use of @code{findVar}, @code{defineVar}
and @code{findFun} (which restricts the search to functions).

To see how this might be applied, here is a simplified internal version
of @code{lapply} for expressions, used as

@smallexample
@group
a <- list(a = 1:5, b = rnorm(10), test = runif(100))
.Call("lapply", a, quote(sum(x)), new.env())
@end group
@end smallexample

@noindent
with C code

@smallexample
@group
SEXP lapply(SEXP list, SEXP expr, SEXP rho)
@{
  int i, n = length(list);
  SEXP ans;

  if(!isNewList(list)) error("`list' must be a list");
  if(!isEnvironment(rho)) error("`rho' should be an environment");
  PROTECT(ans = allocVector(VECSXP, n));
  for(i = 0; i < n; i++) @{
    defineVar(install("x"), VECTOR_ELT(list, i), rho);
    SET_VECTOR_ELT(ans, i, eval(expr, rho));
  @}
  setAttrib(ans, R_NamesSymbol, getAttrib(list, R_NamesSymbol));
  UNPROTECT(1);
  return(ans);
@}
@end group
@end smallexample

It would be closer to @code{lapply} if we could pass in a function
rather than an expression.  One way to do this is @emph{via} interpreted
@R{} code as in the next example, but it is possible (if somewhat
obscure) to do this in C code.  The following is based on the code in
@file{src/main/optimize.c}.

@smallexample
@group
SEXP lapply2(SEXP list, SEXP fn, SEXP rho)
@{
  int i, n = length(list);
  SEXP R_fcall, ans;

  if(!isNewList(list)) error("`list' must be a list");
  if(!isFunction(fn)) error("`fn' must be a function");
  if(!isEnvironment(rho)) error("`rho' should be an environment");
  PROTECT(R_fcall = lang2(fn, R_NilValue));
  PROTECT(ans = allocVector(VECSXP, n));
  for(i = 0; i < n; i++) @{
    SETCADR(R_fcall, VECTOR_ELT(list, i));
    SET_VECTOR_ELT(ans, i, eval(R_fcall, rho));
  @}
  setAttrib(ans, R_NamesSymbol, getAttrib(list, R_NamesSymbol));
  UNPROTECT(2);
  return(ans);
@}
@end group
@end smallexample

@noindent
used by

@smallexample
.Call("lapply2", a, sum, new.env())
@end smallexample

@noindent
Function @code{lang2} creates an executable `list' of two elements, but
this will only be clear to those with a knowledge of a LISP-like
language.

As a more comprehensive example of constructing an @R{} call in C code
and evaluating, consider the following fragment of
@code{printAttributes} in @file{src/main/print.c}.
@smallexample
    /* Need to construct a call to
       print(CAR(a), digits=digits)
       based on the R_print structure, then eval(call, env).
       See do_docall for the template for this sort of thing.
    */
    SEXP s, t;
    PROTECT(t = s = allocList(3));
    SET_TYPEOF(s, LANGSXP);
    CAR(t) = install("print"); t = CDR(t);
    CAR(t) = CAR(a); t = CDR(t);
    CAR(t) = allocVector(INTSXP, 1);
    INTEGER(CAR(t))[0] = digits;
    SET_TAG(t, install("digits"));
    eval(s, env);
    UNPROTECT(1);
@end smallexample

@noindent
At this point @code{CAR(a)} is the @R{} object to be printed, the
current attribute.  There are three steps: the call is constructed as
a pairlist of length 3, the list is filled in, and the expression
represented by the pairlist is evaluated.

A pairlist is quite distinct from a generic vector list, the only
user-visible form of list in @R{}.  A pairlist is a linked list (with
@code{CDR(t)} computing the next entry), with items (accessed by
@code{CAR(t)}) and names or tags (set by @code{SET_TAG}).  In this call
there are to be three items, a symbol (pointing to the function to be
called) and two argument values, the first unnamed and the second named.
Setting the type makes this a call which can be evaluated.


@subsection Zero-finding
@cindex Zero-finding

In this section we re-work the example of @code{call_S} in Becker,
Chambers & Wilks (1988) on finding a zero of a univariate function,
which used to be used as an example for @code{call_R} in the now defunct
@code{demo(dynload)}.  The @R{} code and an example are

@smallexample
zero <- function(f, guesses, tol = 1e-7) @{
  f.check <- function(x) @{
    x <- f(x)
    if(!is.numeric(x)) stop("Need a numeric result")
    as.double(x)
  @}
  .Call("zero", body(f.check), as.double(guesses), as.double(tol),
        new.env())
@}

cube1 <- function(x) (x^2 + 1) * (x - 1.5)
zero(cube1, c(0, 5))
@end smallexample

@noindent
where this time we do the coercion and error-checking in the @R{} code.
The C code is

@smallexample
@group
SEXP mkans(double x)
@{
    SEXP ans;
    PROTECT(ans = allocVector(REALSXP, 1));
    REAL(ans)[0] = x;
    UNPROTECT(1);
    return ans;
@}
@end group

@group
double feval(double x, SEXP f, SEXP rho)
@{
    defineVar(install("x"), mkans(x), rho);
    return(REAL(eval(f, rho))[0]);
@}
@end group

@group
SEXP zero(SEXP f, SEXP guesses, SEXP stol, SEXP rho)
@{
    double x0 = REAL(guesses)[0], x1 = REAL(guesses)[1],
           tol = REAL(stol)[0];
    double f0, f1, fc, xc;
@end group

@group
    if(tol <= 0.0) error("non-positive tol value");
    f0 = feval(x0, f, rho); f1 = feval(x1, f, rho);
    if(f0 == 0.0) return mkans(x0);
    if(f1 == 0.0) return mkans(x1);
    if(f0*f1 > 0.0) error("x[0] and x[1] have the same sign");
@end group

@group
    for(;;) @{
        xc = 0.5*(x0+x1);
        if(fabs(x0-x1) < tol) return  mkans(xc);
        fc = feval(xc, f, rho);
        if(fc == 0) return  mkans(xc);
        if(f0*fc > 0.0) @{
            x0 = xc; f0 = fc;
        @} else @{
            x1 = xc; f1 = fc;
        @}
    @}
@}
@end group
@end smallexample

@noindent
The C code is essentially unchanged from the @code{call_R} version, just
using a couple of functions to convert from @code{double} to @code{SEXP}
and to evaluate @code{f.check}.

@subsection Calculating numerical derivatives
@cindex Numerical derivatives

We will use a longer example (by Saikat DebRoy) to illustrate the use of
evaluation and @code{.External}.  This calculates numerical derivatives,
something that could be done as effectively in interpreted @R{} code but
may be needed as part of a larger C calculation.

An interpreted @R{} version and an example are

@smallexample
@group
numeric.deriv <- function(expr, theta, rho=sys.frame(sys.parent()))
@{
  eps <- sqrt(.Machine$double.eps)
  ans <- eval(substitute(expr), rho)
  grad <- matrix(,length(ans), length(theta),
                 dimnames=list(NULL, theta))
  for (i in seq(along=theta)) @{
    old <- get(theta[i], envir=rho)
    delta <- eps * min(1, abs(old))
    assign(theta[i], old+delta, envir=rho)
    ans1 <- eval(substitute(expr), rho)
    assign(theta[i], old, envir=rho)
    grad[, i] <- (ans1 - ans)/delta
  @}
  attr(ans, "gradient") <- grad
  ans
@}
omega <- 1:5; x <- 1; y <- 2
numeric.deriv(sin(omega*x*y), c("x", "y"))
@end group
@end smallexample

@noindent
where @code{expr} is an expression, @code{theta} a character vector of
variable names and @code{rho} the environment to be used.

For the compiled version the call from @R{} will be

@smallexample
.External("numeric_deriv", @var{expr}, @var{theta}, @var{rho})
@end smallexample

@noindent
with example usage

@smallexample
.External("numeric_deriv", quote(sin(omega*x*y)),
          c("x", "y"), .GlobalEnv)
@end smallexample

@noindent
Note the need to quote the expression to stop it being evaluated.

Here is the complete C code which we will explain section by section.

@smallexample
@group
#include <R.h> /* for DOUBLE_EPS */
#include <Rinternals.h>

SEXP numeric_deriv(SEXP args)
@{
  SEXP theta, expr, rho, ans, ans1, gradient, par, dimnames;
  double tt, xx, delta, eps = sqrt(DOUBLE_EPS);
  int start, i, j;
@end group

@group
  expr = CADR(args);
  if(!isString(theta = CADDR(args)))
    error("theta should be of type character");
  if(!isEnvironment(rho = CADDDR(args)))
    error("rho should be an environment");
@end group

@group
  PROTECT(ans = coerceVector(eval(expr, rho), REALSXP));
  PROTECT(gradient = allocMatrix(REALSXP, LENGTH(ans), LENGTH(theta)));
@end group

@group
  for(i = 0, start = 0; i < LENGTH(theta); i++, start += LENGTH(ans)) @{
    PROTECT(par = findVar(install(CHAR(STRING_ELT(theta, i))), rho));
    tt = REAL(par)[0];
    xx = fabs(tt);
    delta = (xx < 1) ? eps : xx*eps;
    REAL(par)[0] += delta;
    PROTECT(ans1 = coerceVector(eval(expr, rho), REALSXP));
    for(j = 0; j < LENGTH(ans); j++)
      REAL(gradient)[j + start] =
        (REAL(ans1)[j] - REAL(ans)[j])/delta;
    REAL(par)[0] = tt;
    UNPROTECT(2); /* par, ans1 */
  @}
@end group

@group
  PROTECT(dimnames = allocVector(VECSXP, 2));
  SET_VECTOR_ELT(dimnames, 1,  theta);
  dimnamesgets(gradient, dimnames);
  setAttrib(ans, install("gradient"), gradient);
  UNPROTECT(3); /* ans  gradient  dimnames */
  return ans;
@}
@end group
@end smallexample

The code to handle the arguments is

@smallexample
@group
  expr = CADR(args);
  if(!isString(theta = CADDR(args)))
    error("theta should be of type character");
  if(!isEnvironment(rho = CADDDR(args)))
    error("rho should be an environment");
@end group
@end smallexample

@noindent
Note that we check for correct types of @code{theta} and @code{rho} but
do not check the type of @code{expr}.  That is because @code{eval} can
handle many types of @R{} objects other than @code{EXPRSXP}.  There is
no useful coercion we can do, so we stop with an error message if the
arguments are not of the correct mode.

The first step in the code is to evaluate the expression in the
environment @code{rho}, by

@smallexample
  PROTECT(ans = coerceVector(eval(expr, rho), REALSXP));
@end smallexample

@noindent
We then allocate space for the calculated derivative by

@smallexample
  PROTECT(gradient = allocMatrix(REALSXP, LENGTH(ans), LENGTH(theta)));
@end smallexample

@noindent
The first argument to @code{allocMatrix} gives the @code{SEXPTYPE} of
the matrix: here we want it to be @code{REALSXP}.  The other two
arguments are the numbers of rows and columns.

@smallexample
@group
  for(i = 0, start = 0; i < LENGTH(theta); i++, start += LENGTH(ans)) @{
    PROTECT(par = findVar(install(CHAR(STRING_ELT(theta, i))), rho));
@end group
@end smallexample

@noindent
Here, we are entering a for loop.  We loop through each of the
variables.  In the @code{for} loop, we first create a symbol
corresponding to the @code{i}'th element of the @code{STRSXP}
@code{theta}.  Here, @code{STRING_ELT(theta, i)} accesses the
@code{i}'th element of the @code{STRSXP} @code{theta}.  Macro
@code{CHAR()} extracts the actual character representation of it: it
returns a pointer.  We then install the name and use @code{findVar} to
find its value.

@smallexample
@group
    tt = REAL(par)[0];
    xx = fabs(tt);
    delta = (xx < 1) ? eps : xx*eps;
    REAL(par)[0] += delta;
    PROTECT(ans1 = coerceVector(eval(expr, rho), REALSXP));
@end group
@end smallexample

@noindent
We first extract the real value of the parameter, then calculate
@code{delta}, the increment to be used for approximating the numerical
derivative.  Then we change the value stored in @code{par} (in
environment @code{rho}) by @code{delta} and evaluate @code{expr} in
environment @code{rho} again.  Because we are directly dealing with
original @R{} memory locations here, @R{} does the evaluation for the
changed parameter value.

@smallexample
@group
    for(j = 0; j < LENGTH(ans); j++)
      REAL(gradient)[j + start] =
        (REAL(ans1)[j] - REAL(ans)[j])/delta;
    REAL(par)[0] = tt;
    UNPROTECT(2);
  @}
@end group
@end smallexample

@noindent
Now, we compute the @code{i}'th column of the gradient matrix.  Note how
it is accessed: @R{} stores matrices by column (like FORTRAN).

@smallexample
@group
  PROTECT(dimnames = allocVector(VECSXP, 2));
  SET_VECTOR_ELT(dimnames, 1, theta);
  dimnamesgets(gradient, dimnames);
  setAttrib(ans, install("gradient"), gradient);
  UNPROTECT(3);
  return ans;
@}
@end group
@end smallexample

@noindent
First we add column names to the gradient matrix.  This is done by
allocating a list (a @code{VECSXP}) whose first element, the row names,
is @code{NULL} (the default) and the second element, the column names,
is set as @code{theta}.  This list is then assigned as the attribute
having the symbol @code{R_DimNamesSymbol}.  Finally we set the gradient
matrix as the gradient attribute of @code{ans}, unprotect the remaining
protected locations and return the answer @code{ans}.

@node Debugging,  , Evaluating R expressions from C, System and foreign language interfaces
@section Debugging compiled code
@cindex Debugging


Sooner or later programmers will be faced with the need to debug
compiled code loaded into @R{}.  Some ``tricks'' are worth knowing.


@menu
* Finding entry points::
* Inspecting R objects::
@end menu

@node Finding entry points, Inspecting R objects, Debugging, Debugging
@subsection Finding entry points in dynamically loaded code

Under most compilation environments, compiled code dynamically loaded
into @R{} cannot have breakpoints set within it until it is loaded.
To use a symbolic debugger on such dynamically loaded code under UNIX
use

@itemize @bullet
@item
Call the debugger on the R executable, for example by @kbd{R -d gdb}.
@item
Start @R{}.
@item
At the @R{} prompt, use @code{dyn.load} or @code{library} to load your
library.
@item
Send an interrupt signal.  This will put you back to the debugger
prompt.
@item
Set the breakpoints in your code.
@item
Continue execution of R by typing @kbd{signal 0@key{RET}}.
@end itemize

Under Windows the @R{} engine is itself in a DLL, and the procedure is

@itemize @bullet
@item
Start @R{} under the debugger after setting a breakpoint for
@code{WinMain}.

@smallexample
@group
gdb .../bin/Rgui.exe
(gdb) break WinMain
(gdb) run
[ stops with R.dll loaded ]
(gdb) break R_ReadConsole
(gdb) continue
[ stops with console running ]
(gdb) continue
@end group
@end smallexample

@item
At the @R{} prompt, use @code{dyn.load} or @code{library} to load your library.
@item
Set the breakpoints in your code.
@item
Use

@smallexample
@group
(gdb) clear R_ReadConsole
(gdb) continue
@end group
@end smallexample

@noindent
to continue running with the breakpoints set.
@end itemize

@noindent
Windows has little support for signals, so the usual idea of running a
program under a debugger and sending it a signal to interrupt it and
drop control back to the debugger only works with some debuggers.

@node Inspecting R objects,  , Finding entry points, Debugging
@subsection Inspecting R objects when debugging
@cindex Inspecting R objects when debugging

The key to inspecting @R{} objects from compiled code is the function
@code{PrintValue(SEXP @var{s})} which uses the normal @R{} printing
mechanisms to print the @R{} object pointed to by @var{s}, or the safer
version @code{R_PV(SEXP @var{s})} which will only print `objects'.

One way to make use to @code{PrintValue} is to insert suitable calls
into the code to be debugged.

Another way is to call @code{R_PV} from the symbolic debugger.
(@code{PrintValue} is hidden as @code{Rf_PrintValue}.)  For example,
from @code{gdb} we can use

@smallexample
(gdb) p R_PV(ab)
@end smallexample

@noindent
using the object @code{ab} from the convolution example, if we have
placed a suitable breakpoint in the convolution C code.

To examine an arbitrary @R{} object we need to work a little harder.
For example, let

@smallexample
R> DF <- data.frame(a = 1:3, b = 4:6)
@end smallexample

@noindent
By setting a breakpoint at @code{do_get} and typing @kbd{get("DF")} at
the R prompt, one can find out the address in memory of @code{DF}, for
example

@smallexample
@group
Value returned is $1 = (SEXPREC *) 0x40583e1c
(gdb) p *$1
$2 = @{
  sxpinfo = @{type = 19, obj = 1, named = 1, gp = 0,
    mark = 0, debug = 0, trace = 0, = 0@},
  attrib = 0x40583e80,
  u = @{
    vecsxp = @{
      length = 2,
      type = @{c = 0x40634700 "0>X@@D>X@@0>X@@", i = 0x40634700,
        f = 0x40634700, z = 0x40634700, s = 0x40634700@},
      truelength = 1075851272,
    @},
    primsxp = @{offset = 2@},
    symsxp = @{pname = 0x2, value = 0x40634700, internal = 0x40203008@},
    listsxp = @{carval = 0x2, cdrval = 0x40634700, tagval = 0x40203008@},
    envsxp = @{frame = 0x2, enclos = 0x40634700@},
    closxp = @{formals = 0x2, body = 0x40634700, env = 0x40203008@},
    promsxp = @{value = 0x2, expr = 0x40634700, env = 0x40203008@}
  @}
@}
@end group
@end smallexample

@noindent
(Debugger output reformatted for better legibility).

Using @code{R_PV()} one can ``inspect'' the values of the various
elements of the SEXP, for example,

@smallexample
@group
(gdb) p R_PV($1->attrib)
$names
[1] "a" "b"

$row.names
[1] "1" "2" "3"

$class
[1] "data.frame"

$3 = void
@end group
@end smallexample

To find out where exactly the corresponding information is stored, one
needs to go ``deeper'':

@smallexample
@group
(gdb) set $a = $1->attrib
(gdb) p $a->u.listsxp.tagval->u.symsxp.pname->u.vecsxp.type.c
$4 = 0x405d40e8 "names"
(gdb) p $a->u.listsxp.carval->u.vecsxp.type.s[1]->u.vecsxp.type.c
$5 = 0x40634378 "b"
(gdb) p $1->u.vecsxp.type.s[0]->u.vecsxp.type.i[0]
$6 = 1
(gdb) p $1->u.vecsxp.type.s[1]->u.vecsxp.type.i[1]
$7 = 5
@end group
@end smallexample

@node The R API, Generic functions and methods, System and foreign language interfaces, Top
@chapter The R @acronym{API}: entry points for C code

@menu
* Memory allocation::
* Error handling::
* Random numbers::
* Missing and IEEE values::
* Printing::
* Calling C from FORTRAN and vice versa::
* Numerical analysis subroutines::
* Optimization::
* Integration::
* Utility functions::
* Platform and version information::
* Standalone Mathlib::
@end menu

There are a large number of entry points in the @R{} executable/DLL that
can be called from C code (and some that can be called from FORTRAN
code).  Only those documented here are stable enough that they will only
be changed with considerable notice.

The recommended procedure to use these is to include the header file
@file{R.h} in your C code by

@smallexample
#include <R.h>
@end smallexample

@noindent
This will include several other header files from the directory
@file{@var{R_HOME}/include/R_ext}, and there are other header files
there that can be included too, but many of the features they contain
should be regarded as undocumented and unstable.

An alternative is to include the header file @file{S.h}, which may be
useful when porting code from @Sl{}.  This includes rather less than
@file{R.h}, and has extra some compatibility definitions (for example
the @code{S_complex} type from @Sl{}).

The defines used for compatibility with @Sl{} sometimes causes
conflicts@footnote{notably with Windows headers}, and the known
problematic defines can be removed by defining @code{STRICT_R_HEADERS}.

Most of these header files, including all those included by @file{R.h},
can be used from C++ code.

@quotation
@strong{Note:} Because @R{} re-maps many of its external names to avoid
clashes with user code, it is @emph{essential} to include the
appropriate header files when using these entry points.
@end quotation

This remapping can cause problems@footnote{known problems are redefining
@code{error}, @code{length}, @code{vector} and @code{warning}}, and it
can be eliminated by defining @code{R_NO_REMAP} and prepending
@code{Rf_} to @emph{all} the function names used from
@file{Rinternals.h} and @file{R_exts/Error.h}.

@node Memory allocation, Error handling, The R API, The R API
@section Memory allocation
@cindex Memory allocation from C

@menu
* Transient::
* User-controlled::
@end menu

There are two types of memory allocation available to the C programmer,
one in which @R{} manages the clean-up and the other in which user
has full control (and responsibility).

@node Transient, User-controlled, Memory allocation, Memory allocation
@subsection Transient storage allocation
@findex R_alloc
@findex S_alloc
@findex S_realloc
@findex vmaxget
@findex vmaxset

Here @R{} will reclaim the memory at the end of the call to @code{.C}.
Use

@smallexample
char* R_alloc(long @var{n}, int @var{size})
@end smallexample

@noindent
which allocates @var{n} units of @var{size} bytes each.  A typical usage
(from package @pkg{mva}) is

@smallexample
x = (int *) R_alloc(nrows(merge)+2, sizeof(int));
@end smallexample

There is a similar call, @code{S_alloc}, for compatibility with @Sl{},
which differs only in zeroing the memory allocated, and

@smallexample
S_realloc(char *@var{p}, long @var{new}, long @var{old}, int @var{size})
@end smallexample

@noindent
which changes the allocation size from @var{old} to @var{new} units, and
zeroes the additional units.

This memory is taken from the heap, and released at the end of the
@code{.C}, @code{.Call} or @code{.External} call.  Users can also manage
it, by noting the current position with a call to @code{vmaxget} and
clearing memory allocated subsequently by a call to @code{vmaxset}.
This is only recommended for experts.

@node User-controlled,  , Transient, Memory allocation
@subsection User-controlled memory
@findex Calloc
@findex Realloc
@findex Free

The other form of memory allocation is an interface to @code{malloc},
the interface providing @R{} error handling.  This memory lasts until
freed by the user and is additional to the memory allocated for the @R{}
workspace.

The interface functions are

@smallexample
@group
@var{type}* Calloc(size_t @var{n}, @var{type})
@var{type}* Realloc(@var{any} *@var{p}, size_t @var{n}, @var{type})
void Free(@var{any} *@var{p})
@end group
@end smallexample

@noindent
providing analogues of @code{calloc}, @code{realloc} and @code{free}.
If there is an error it is handled by @R{}, so if these routines return
the memory has been successfully allocated or freed.  @code{Free} will
set the pointer @var{p} to @code{NULL}.  (Some but not all versions of
@Sl{} do so.)

@node Error handling, Random numbers, Memory allocation, The R API
@section Error handling
@cindex Error handling from C

The basic error handling routines are the equivalents of @code{stop} and
@code{warning} in @R{} code, and use the same interface.

@smallexample
@group
void error(const char * @var{format}, ...);
void warning(const char * @var{format}, ...);
@end group
@end smallexample

@noindent
These have the same call sequences as calls to @code{printf}, but in the
simplest case can be called with a single character string argument
giving the error message. (Don't do this if the string contains @samp{%}
or might otherwise be interpreted as a format.)

If @code{STRICT_R_HEADERS} is not defined there is also an
@Sl{}-compatibility interface which uses calls of the form

@smallexample
@group
PROBLEM ...... ERROR
MESSAGE ...... WARN
PROBLEM ...... RECOVER(NULL_ENTRY)
MESSAGE ...... WARNING(NULL_ENTRY)
@end group
@end smallexample

@noindent
the last two being the forms available in all @Sl{} versions.  Here
@samp{......} is a set of arguments to @code{printf}, so can be a string
or a format string followed by arguments separated by commas.

@subsection Error handling from FORTRAN
@cindex Error handling from FORTRAN

There are two interface function provided to call @code{error} and
@code{warning} from FORTRAN code, in each case with a simple character
string argument.  They are defined as

@smallexample
@group
subroutine rexit(@var{message})
subroutine rwarn(@var{message})
@end group
@end smallexample

Messages of more than 255 characters are truncated, with a warning.

@node Random numbers, Missing and IEEE values, Error handling, The R API
@section Random number generation
@cindex Random numbers in C
@findex unif_rand
@findex norm_rand
@findex exp_rand
@findex GetRNGstate
@findex PutRNGstate
@findex .Random.seed
@findex seed_in
@findex seed_out

The interface to @R{}'s internal random number generation routines is

@smallexample
@group
double unif_rand();
double norm_rand();
double exp_rand();
@end group
@end smallexample

@noindent
giving one uniform, normal or exponential pseudo-random variate.
However, before these are used, the user must call

@smallexample
GetRNGstate();
@end smallexample

@noindent
and after all the required variates have been generated, call

@smallexample
PutRNGstate();
@end smallexample

@noindent
These essentially read in (or create) @code{.Random.seed} and write it
out after use.

File @file{S.h} defines @code{seed_in} and @code{seed_out} for
@Sl{}-compatibility rather than @code{GetRNGstate} and
@code{PutRNGstate}.  These take a @code{long *} argument which is
ignored.

The random number generator is private to @R{}; there is no way to
select the kind of RNG or set the seed except by evaluating calls to the
@R{} functions.

The C code behind @R{}'s @code{r@var{xxx}} functions can be accessed by
including the header file @file{Rmath.h}; @xref{Distribution
functions}.  Those calls generate a single variate and should also be
enclosed in calls to @code{GetRNGstate} and @code{PutRNGstate}.

@comment MM: FIXME   void rmultinom() is different, returning a vector!

@node Missing and IEEE values, Printing, Random numbers, The R API
@section Missing and @acronym{IEEE} special values
@cindex Missing values
@cindex IEEE special values
@findex ISNA
@findex ISNAN
@findex R_FINITE
@findex R_IsNaN
@findex R_PosInf
@findex R_NegInf
@findex NA_REAL

It is possible to compile @R{} on a platform without @acronym{IEC} 559
(more commonly known as @acronym{IEEE} 754)-compatible arithmetic, so
users should not assume that it is available.  Rather a set of functions
is provided to test for @code{NA}, @code{Inf}, @code{-Inf} (which exists
on all platforms) and @code{NaN}.  These functions are accessed via
macros:

@smallexample
@group
ISNA(@var{x})        @r{True for R's @code{NA} only}
ISNAN(@var{x})       @r{True for R's @code{NA} and @acronym{IEEE} @code{NaN}}
R_FINITE(@var{x})    @r{False for @code{Inf}, @code{-Inf}, @code{NA}, @code{NaN}}
@end group
@end smallexample

@noindent
and function @code{R_IsNaN} is true for @code{NaN} but not @code{NA}.
Do use these rather than @code{isnan} or @code{finite}; the latter in
particular is often mendacious.

You can check for @code{Inf} or @code{-Inf} by testing equality to
@code{R_PosInf} or @code{R_NegInf}, and set (but not test) an @code{NA}
as @code{NA_REAL}.

All of the above apply to @emph{double} variables only.  For integer
variables there is a variable accessed by the macro @code{NA_INTEGER}
which can used to set or test for missingness.

Beware that these special values may be represented by extreme values
which could occur in ordinary computations which run out of control,
so you may need to test that they have not been generated inadvertently.


@node Printing, Calling C from FORTRAN and vice versa, Missing and IEEE values, The R API
@section Printing
@cindex Printing from C
@findex Rprintf
@findex REprintf
@findex Rvprintf
@findex REvprintf

The most useful function for printing from a C routine compiled into
@R{} is @code{Rprintf}.  This is used in exactly the same way as
@code{printf}, but is guaranteed to write to @R{}'s output (which might
be a @acronym{GUI} console rather than a file).  It is wise to write
complete lines (including the @code{"\n"}) before returning to @R{}.

The function @code{REprintf} is similar but writes on the error stream
(@code{stderr}) which may or may not be different from the standard
output stream.  Functions @code{Rvprintf} and @code{REvprintf} are the
analogues using the @code{vprintf} interface.


@subsection Printing from FORTRAN
@cindex Printing from FORTRAN

In theory FORTRAN @code{write} and @code{print} statements can be used,
but the output may not interleave well with that of C, and will be
invisible on @acronym{GUI} interfaces.  They are best avoided.

Three subroutines are provided to ease the output of information from
FORTRAN code.

@smallexample
@group
subroutine dblepr(@var{label}, @var{nchar}, @var{data}, @var{ndata})
subroutine realpr(@var{label}, @var{nchar}, @var{data}, @var{ndata})
subroutine intpr (@var{label}, @var{nchar}, @var{data}, @var{ndata})
@end group
@end smallexample

@noindent
Here @var{label} is a character label of up to 255 characters,
@var{nchar} is its length (which can be @code{-1} if the whole label is
to be used), and @var{data} is an array of length at least @var{ndata}
of the appropriate type (@code{double precision}, @code{real} and
@code{integer} respectively).  These routines print the label on one
line and then print @var{data} as if it were an @R{} vector on
subsequent line(s).  They work with zero @var{ndata}, and so can be used
to print a label alone.

@node Calling C from FORTRAN and vice versa, Numerical analysis subroutines, Printing, The R API
@section Calling C from FORTRAN and vice versa
@cindex Calling C from FORTRAN and vice versa

Naming conventions for symbols generated by FORTRAN differ by platform:
it is not safe to assume that FORTRAN names appear to C with a trailing
underscore.  To help cover up the platform-specific differences there is
a set of macros that should be used.

@table @code
@item F77_SUB(@var{name})
to define a function in C to be called from FORTRAN
@item F77_NAME(@var{name})
to declare a FORTRAN routine in C before use
@item F77_CALL(@var{name})
to call a FORTRAN routine from C
@item F77_COMDECL(@var{name})
to declare a FORTRAN common block in C
@item F77_COM(@var{name})
to access a FORTRAN common block from C
@end table

On most current platforms these are all the same, but it is unwise to
rely on this.

For example, suppose we want to call R's normal random numbers from
FORTRAN.  We need a C wrapper along the lines of

@smallexample
@group
#include <R.h>

void F77_SUB(rndstart)(void) @{ GetRNGstate(); @}
void F77_SUB(rndend)(void) @{ PutRNGstate(); @}
double F77_SUB(normrnd)(void) @{ return norm_rand(); @}
@end group
@end smallexample

@noindent
to be called from FORTRAN as in

@smallexample
@group
      subroutine testit()
      double precision normrnd, x
      call rndstart()
      x = normrnd()
      call dblepr("X was", 5, x, 1)
      call rndend()
      end
@end group
@end smallexample

@noindent
Note that this is not guaranteed to be portable, for the return
conventions might not be compatible between the C and FORTRAN compilers
used.  (Passing values via arguments is safer.)

The standard packages, for example @pkg{modreg}, are a rich source of
further examples.



@node Numerical analysis subroutines, Optimization, Calling C from FORTRAN and vice versa, The R API
@section Numerical analysis subroutines
@cindex Numerical analysis subroutines from C

@R{} contains a large number of mathematical functions for its own use,
for example numerical linear algebra computations and special functions.

@c FIXME: Change this paragraph!
@c 1. @file{R_ext/BLAS.h}
@c 2. @file{R_ext/Lapack.h}
@c 3. @file{R_ext/Linpack.h} is older and you should use Lapack.h,
@c    but we won't drop support for it soon...
The header file @file{R_ext/Linpack.h} contains details of the BLAS,
LINPACK and EISPACK linear algebra functions included in @R{}.  These
are expressed as calls to FORTRAN subroutines, and they will also be
usable from users' FORTRAN code.  Although not part of the official
@acronym{API}, this set of subroutines is unlikely to change (but might
be supplemented).

The header file @file{Rmath.h} lists many other functions that are
available and documented in the following subsections. Many of these are
C interfaces to the code behind @R{} functions, so the @R{} function
documentation may give further details.

@menu
* Distribution functions::
* Mathematical functions::
* Utilities::
* Mathematical constants::
@end menu

@node Distribution functions, Mathematical functions, Numerical analysis subroutines, Numerical analysis subroutines
@subsection Distribution functions
@cindex  Distribution functions from C

The routines used to calculate densities, cumulative distribution
functions and quantile functions for the standard statistical
distributions are available as entry points.

The arguments for the entry points follow the pattern of those for the
normal distribution:

@smallexample
@group
double dnorm(double @var{x}, double @var{mu}, double @var{sigma}, int @var{give_log});
double pnorm(double @var{x}, double @var{mu}, double @var{sigma}, int @var{lower_tail},
             int @var{give_log});
double qnorm(double @var{p}, double @var{mu}, double @var{sigma}, int @var{lower_tail},
             int @var{log_p});
double rnorm(double @var{mu}, double @var{sigma});
@end group
@end smallexample

@noindent
That is, the first argument gives the position for the density and CDF
and probability for the quantile function, followed by the
distribution's parameters.  Argument @var{lower_tail} should be
@code{TRUE} (or @code{1}) for normal use, but can be @code{FALSE} (or
@code{0}) if the probability of the upper tail is desired or specified.

Finally, @var{give_log} should be non-zero if the result is required on
log scale, and @var{log_p} should be non-zero if @var{p} has been
specified on log scale.

Note that you directly get the cumulative (or ``integrated'')
@emph{hazard} function, @eqn{H(t) = - \log(1 - F(t)), H(t) = - log(1 -
F(t))}, by using

@smallexample
- p@var{dist}(t, ..., /*lower_tail = */ FALSE, /* give_log = */ TRUE)
@end smallexample

@noindent
or shorter (and more cryptic) @code{- p@var{dist}(t, ..., 0, 1)}.
@cindex cumulative hazard

The random-variate generation routine @code{rnorm} returns one normal
variate. @xref{Random numbers}, for the protocol in using the
random-variate routines.
@cindex Random numbers in C

Note that these argument sequences are (apart from the names and that
@code{rnorm} has no @var{n}) exactly the same as the corresponding @R{}
functions of the same name, so the documentation of the @R{} functions
can be used.

For reference, the following table gives the basic name (to be prefixed
by @samp{d}, @samp{p}, @samp{q} or @samp{r} apart from the exceptions
noted) and distribution-specific arguments for the complete set of
distributions.

@quotation
@multitable @columnfractions .28 .22 .30
@item beta @tab @code{beta} @tab @code{a}, @code{b}
@item non-central beta @tab @code{nbeta} @tab @code{a}, @code{b}, @code{lambda}
@item binomial @tab @code{binom} @tab @code{n}, @code{p}
@item Cauchy @tab @code{cauchy} @tab @code{location}, @code{scale}
@item chi-squared @tab @code{chisq} @tab @code{df}
@item non-central chi-squared @tab @code{nchisq} @tab @code{df}, @code{lambda}
@item exponential @tab @code{exp} @tab @code{scale}
@item F @tab @code{f} @tab @code{n1}, @code{n2}
@item non-central F @tab @code{nf} (*) @tab @code{n1}, @code{n2}, @code{ncp}
@item gamma @tab @code{gamma} @tab @code{shape}, @code{scale}
@item geometric @tab @code{geom} @tab @code{p}
@item hypergeometric @tab @code{hyper} @tab @code{NR}, @code{NB}, @code{n}
@item logistic @tab @code{logis} @tab @code{location}, @code{scale}
@item lognormal @tab @code{lnorm} @tab @code{logmean}, @code{logsd}
@item negative binomial @tab @code{nbinom} @tab @code{n}, @code{p}
@item normal @tab @code{norm} @tab @code{mu}, @code{sigma}
@item Poisson @tab @code{pois} @tab @code{lambda}
@item Student's t @tab @code{t} @tab @code{n}
@item non-central t @tab @code{nt} (*) @tab @code{df}, @code{delta}
@item Studentized range @tab @code{tukey} (*) @tab @code{rr}, @code{cc}, @code{df}
@item uniform @tab @code{unif} @tab @code{a}, @code{b}
@item Weibull @tab @code{weibull} @tab @code{shape}, @code{scale}
@item Wilcoxon rank sum @tab @code{wilcox} @tab @code{m}, @code{n}
@item Wilcoxon signed rank @tab @code{signrank} @tab @code{n}
@end multitable
@end quotation

@noindent
Entries marked only have @samp{p} and @samp{q} functions available.
After a call to @code{dwilcox}, @code{pwilcox} or @code{qwilcox} the
function @code{wilcox_free()} should be called, and similarly for the
signed rank functions.

The argument names are not all quite the same as the @R{} ones.
@c ^^^ FIXME ?? (argument names in the C code wouldn't change the API ..) ^^
@c {don't want to change the R function argument names} -- <<

@node Mathematical functions, Utilities, Distribution functions, Numerical analysis subroutines
@subsection Mathematical functions

@findex gammafn
@findex lgammafn
@findex digamma
@findex trigamma
@findex tetragamma
@findex pentagamma
@cindex Gamma function
@deftypefun double gammafn (double @var{x})
@deftypefunx double lgammafn (double @var{x})
@deftypefunx double digamma (double @var{x})
@deftypefunx double trigamma (double @var{x})
@deftypefunx double tetragamma (double @var{x})
@deftypefunx double pentagamma (double @var{x})
The Gamma function, its natural logarithm and first four derivatives.
@end deftypefun

@findex beta
@findex lbeta
@cindex Beta function
@deftypefun double beta (double @var{a}, double @var{b})
@deftypefunx double lbeta (double @var{a}, double @var{b})
The (complete) Beta function and its natural logarithm.
@end deftypefun

@findex choose
@findex lchoose
@deftypefun double choose (double @var{n}, double @var{k})
@deftypefunx double lchoose (double @var{n}, double @var{k})
The number of combinations of @var{k} items chosen from from @var{n} and
its natural logarithm.  @var{n} and @var{k} are rounded to the nearest
integer.
@end deftypefun

@findex bessel_i
@findex bessel_j
@findex bessel_k
@findex bessel_y
@cindex Bessel functions
@deftypefun double bessel_i (double @var{x}, double @var{nu}, double @var{expo})
@deftypefunx double bessel_j (double @var{x}, double @var{nu})
@deftypefunx double bessel_k (double @var{x}, double @var{nu}, double @var{expo})
@deftypefunx double bessel_y (double @var{x}, double @var{nu})
Bessel functions of types I, J, K and Y with index @var{nu}.  For
@code{bessel_i} and @code{bessel_k} there is the option to return
@w{exp(-@var{x}) I(@var{x}; @var{nu})} or @w{exp(@var{x}) K(@var{x};
@var{nu})} if @var{expo} is 2. (Use @code{@var{expo} == 1} for unscaled
values.)
@end deftypefun


@node Utilities, Mathematical constants, Mathematical functions, Numerical analysis subroutines
@subsection Utilities
There are a few other numerical utility functions available as entry points.


@deftypefun double R_pow (double @var{x}, double @var{y})
@deftypefunx double R_pow_di (double @var{x}, int @var{i})
@code{R_pow(@var{x}, @var{y})} and @code{R_pow_di(@var{x}, @var{i})}
compute @code{@var{x}^@var{y}} and @code{@var{x}^@var{i}}, respectively
using @code{R_FINITE} checks and returning the proper result (the same
as @R{}) for the cases where @var{x}, @var{y} or @var{i} are 0 or
missing or infinite or @code{NaN}.
@end deftypefun

@deftypefun double pythag (double @var{a}, double @var{b})
@code{pythag(@var{a}, @var{b})} computes @code{sqrt(@var{a}^2 +
@var{b}^2)} without overflow or destructive underflow: for example it
still works when both @var{a} and @var{b} are between @code{1e200} and
@code{1e300} (in @acronym{IEEE} double precision).
@end deftypefun

@deftypefun double log1p (@var{x})
Computes @code{log(1 + @var{x})} (@emph{log 1 @b{p}lus x}), accurately
even for small @var{x}, i.e., @eqn{|x| \ll 1, |x| << 1}.

This may be provided by your platform, in which case it is not
included in @file{Rmath.h}, but is (probably) in @file{math.h}.  For
backwards compatibility with @R{} versions prior to 1.5.0, the entry
point @code{Rf_log1p} is still provided.
@end deftypefun

@deftypefun double expm1 (@var{x})
Computes @code{exp(@var{x}) - 1} (@emph{exp x @b{m}inus 1}), accurately
even for small @var{x}, i.e., @eqn{|x| \ll 1, |x| << 1}.

This may be provided by your platform, in which case it is not
included in @file{Rmath.h}, but is (probably) in @file{math.h}.
@end deftypefun

@deftypefun int imax2 (int @var{x}, int @var{y})
@deftypefunx int imin2 (int @var{x}, int @var{y})
@deftypefunx double fmax2 (double @var{x}, double @var{y})
@deftypefunx double fmin2 (double @var{x}, double @var{y})
Return the larger (@code{max}) or smaller (@code{min}) of two integer or
double numbers, respectively.
@end deftypefun

@deftypefun double sign (double @var{x})
Compute the @emph{signum} function, where sign(@var{x}) is 1, 0, or
@math{-1}, when @var{x} is positive, 0, or negative, respectively.
@end deftypefun

@deftypefun double fsign (double @var{x}, double @var{y})
Performs ``transfer of sign'' and is defined as @eqn{|x| *
\hbox{sign}(y), |x| * sign(x)}.
@end deftypefun

@deftypefun double fprec (double @var{x}, double @var{digits})
Returns the value of @var{x} rounded to @var{digits} decimal digits
(after the decimal point).

This is the function used by @R{}'s @code{round()}.
@end deftypefun

@deftypefun double fround (double @var{x}, double @var{digits})
Returns the value of @var{x} rounded to @var{digits} @emph{significant}
decimal digits.

This is the function used by @R{}'s @code{signif()}.
@end deftypefun

@deftypefun double ftrunc (double @var{x})
Returns the value of @var{x} truncated (to an integer value) towards zero.
@end deftypefun

@node Mathematical constants,  , Utilities, Numerical analysis subroutines
@subsection Mathematical constants
@findex M_E
@findex M_PI
@c maybe not all into the index ...

@R{} has a set of commonly used mathematical constants encompassing
constants usually found @file{math.h} and contains further ones that are
used in statistical computations.  All these are defined to (at least)
30 digits accuracy in @file{Rmath.h}.  The following definitions
use @code{ln(x)} for the natural logarithm (@code{log(x)} in @R{}).

@quotation
@multitable {Name can be long}  {Definition (needs space)}  {0.123456789012345678 ...}

@item @strong{Name} @tab @strong{Definition (@code{ln = log})} @tab @strong{round(@emph{value}, 7)}

@c SVID & X/Open Constants -- names from Solaris math.h :
@item @code{M_E} @tab @math{e} @tab 2.7182818
@item @code{M_LOG2E} @tab log2(@math{e}) @tab 1.4426950
@item @code{M_LOG10E} @tab log10(@math{e}) @tab 0.4342945
@item @code{M_LN2} @tab ln(2) @tab 0.6931472
@item @code{M_LN10} @tab ln(10) @tab 2.3025851
@item @code{M_PI} @tab @eqn{\pi, pi}   @tab 3.1415927
@item @code{M_PI_2} @tab @eqn{\pi/2, pi/2} @tab 1.5707963
@item @code{M_PI_4} @tab @eqn{\pi/4, pi/4} @tab 0.7853982
@item @code{M_1_PI} @tab @eqn{1/\pi, 1/pi} @tab 0.3183099
@item @code{M_2_PI} @tab @eqn{2/\pi, 2/pi} @tab 0.6366198
@item @code{M_2_SQRTPI} @tab 2/sqrt(@eqn{\pi, pi}) @tab 1.1283792
@item @code{M_SQRT2} @tab sqrt(2) @tab 1.4142136
@item @code{M_SQRT1_2} @tab 1/sqrt(2) @tab 0.7071068
@c R-specific ones
@item @code{M_SQRT_3} @tab sqrt(3) @tab 1.7320508
@item @code{M_SQRT_32} @tab sqrt(32) @tab 5.6568542
@item @code{M_LOG10_2} @tab log10(2) @tab 0.3010300
@item @code{M_2PI} @tab @eqn{2\pi, 2*pi} @tab 6.2831853
@item @code{M_SQRT_PI} @tab sqrt(@eqn{\pi, pi}) @tab 1.7724539
@item @code{M_1_SQRT_2PI} @tab 1/sqrt(@eqn{2\pi, 2*pi}) @tab 0.3989423
@item @code{M_SQRT_2dPI} @tab sqrt(2/@eqn{\pi, pi}) @tab 0.7978846
@item @code{M_LN_SQRT_PI} @tab ln(sqrt(@eqn{\pi, pi})) @tab 0.5723649
@item @code{M_LN_SQRT_2PI} @tab ln(sqrt(@eqn{2\pi, 2*pi})) @tab 0.9189385
@item @code{M_LN_SQRT_PId2} @tab ln(sqrt(@eqn{\pi, pi}/2)) @tab 0.2257914
@end multitable
@end quotation

There are a set of constants (@code{PI}, @code{DOUBLE_EPS}) (and so on)
defined@footnote{unless @code{STRICT_R_HEADERS} is defined} in the
included header @file{R_ext/Constants.h}, mainly for compatibility with
@Sl{}.

@findex TRUE
@findex FALSE
Further, the included header @file{R_ext/Boolean.h} has constants
@code{TRUE} and @code{FALSE = 0} of type @code{Rboolean} in order to
provide a way of using ``logical'' variables in C consistently.


@node Optimization, Integration, Numerical analysis subroutines, The R API
@section Optimization
@cindex optimization

The C code underlying @code{optim} can be accessed directly.  The user
needs to supply a function to compute the function to be minimized, of
the type

@smallexample
typedef double optimfn(int n, double *par, void *ex);
@end smallexample

@noindent
where the first argument is the number of parameters in the second
argument.  The third argument is a pointer passed down from the calling
routine, normally used to carry auxiliary information.

Some of the methods also require a gradient function

@smallexample
typedef void optimgr(int n, double *par, double *gr, void *ex);
@end smallexample

@noindent
which passes back the gradient in the @code{gr} argument.  No function
is provided for finite-differencing, nor for approximating the Hessian
at the result.

The interfaces are

@itemize @bullet
@item Nelder Mead:
@findex nmmin
@smallexample
void nmmin(int n, double *xin, double *x, double *Fmin, optimfn fn,
           int *fail, double abstol, double intol, void *ex,
           double alpha, double beta, double gamma, int trace,
           int *fncount, int maxit);
@end smallexample

@item BFGS:
@findex vmmin
@smallexample
void vmmin(int n, double *x, double *Fmin,
           optimfn fn, optimgr gr, int maxit, int trace,
           int *mask, double abstol, double reltol, int nREPORT,
           void *ex, int *fncount, int *grcount, int *fail);
@end smallexample

@item Conjugate gradients:
@findex cgmin
@smallexample
void cgmin(int n, double *xin, double *x, double *Fmin,
           optimfn fn, optimgr gr, int *fail, double abstol,
           double intol, void *ex, int type, int trace,
           int *fncount, int *grcount, int maxit);
@end smallexample

@item Limited-memory BFGS with bounds:
@findex lbfgsb
@smallexample
void lbfgsb(int n, int lmm, double *x, double *lower,
            double *upper, int *nbd, double *Fmin, optimfn fn,
            optimgr gr, int *fail, void *ex, double factr,
            double pgtol, int *fncount, int *grcount,
            int maxit, char *msg, int trace, int nREPORT);
@end smallexample

@item Simulated annealing:
@findex samin
@smallexample
void samin(int n, double *x, double *Fmin, optimfn fn, int maxit,
           int tmax, double temp, int trace, void *ex);
@end smallexample

@end itemize

@noindent
Many of the arguments are common to the various methods.  @code{n} is
the number of parameters, @code{x} or @code{xin} is the starting
parameters on entry and @code{x} the final parameters on exit, with
final value returned in @code{Fmin}.  Most of the other parameters can
be found from the help page for @code{optim}: see the source code
@file{src/appl/lbfgsb.c} for the values of @code{nbd}, which
specifies which bounds are to be used.


@node Integration, Utility functions, Optimization, The R API
@section Integration
@cindex integration

The C code underlying @code{integrate} can be accessed directly.  The
user needs to supply a @emph{vectorizing} C function to compute the
function to be integrated, of the type

@smallexample
typedef void integr_fn(double *x, int n, void *ex);
@end smallexample

@noindent
where @code{x[]} is both input and output and has length @code{n}, i.e.,
a C function, say @code{fn}, of type @code{integr_fn} must basically do
@code{for(i in 1:n) x[i] := f(x[i], ex)}.  The vectorization requirement
can be used to speed up the integrand instead of calling it @code{n}
times.  Note that in the current implementation built on QUADPACK,
@code{n} will be either 15 or 21.  The @code{ex} argument is a pointer
passed down from the calling routine, normally used to carry auxiliary
information.

There are interfaces for definite and for indefinite integrals.
`Indefinite' means that at least one of the integration boundaries is
not finite.

@itemize @bullet
@item Finite:
@findex Rdqags
@smallexample
void Rdqags(integr_fn f, void *ex, double *a, double *b,
            double *epsabs, double *epsrel,
            double *result, double *abserr, int *neval, int *ier,
            int *limit, int *lenw, int *last,
            int *iwork, double *work);
@end smallexample

@item Indefinite:
@findex Rdqagi
@smallexample
void Rdqagi(integr_fn f, void *ex, double *bound, int *inf,
            double *epsabs, double *epsrel,
            double *result, double *abserr, int *neval, int *ier,
            int *limit, int *lenw, int *last,
            int *iwork, double *work);
@end smallexample

@end itemize

@noindent
Only the 3rd and 4th argument differ for the two integrators; for the
definite integral, using @code{Rdqags}, @code{a} and @code{b} are the
integration interval bounds, whereas for an indefinite integral, using
@code{Rdqagi}, @code{bound} is the finite bound of the integration (if
the integral is not doubly-infinite) and @code{inf} is a code indicating
the kind of integration range,

@table @code
@item inf = 1
      corresponds to (bound, +Inf),
@item inf = -1
      corresponds to (-Inf, bound),
@item inf = 2
      corresponds to (-Inf, +Inf),
@end table

@code{f} and @code{ex} define the integrand function, see above;
@code{epsabs} and @code{epsrel} specify the absolute and relative
accuracy requested, @code{result}, @code{abserr} and @code{last} are the
output components @code{value}, @code{abs.err} and @code{subdivisions}
of the @R{} function integrate, where @code{neval} gives the number of
integrand function evaluations, and the error code @code{ier} is
translated to @R{}'s @code{integrate() $ message}, look at that function
definition.  @code{limit} corresponds to @code{integrate(...,
subdivisions = *)}.  It seems you should always define the two work
arrays and the length of the second one as

@smallexample
    lenw = 4 * limit;
    iwork =   (int *) R_alloc(limit, sizeof(int));
    work = (double *) R_alloc(lenw,  sizeof(double));
@end smallexample

The comments in the source code in @file{src/appl/integrate.c} give
more details, particularly about reasons for failure (@code{ier >= 1}).

@node Utility functions, Platform and version information, Integration, The R API
@section Utility functions
@cindex Sort functions from C

@R{} has a fairly comprehensive set of sort routines which are made
available to users' C code.  These include the following.

@deftypefun void R_isort (int* @var{x}, int @var{n})
@deftypefunx void R_rsort (double* @var{x}, int @var{n})
@deftypefunx void R_csort (Rcomplex* @var{x}, int @var{n})
@deftypefunx void rsort_with_index (double* @var{x}, int* @var{index}, int @var{n})
The first three sort integer, real (double) and complex data
respectively.  (Complex numbers are sorted by the real part first then
the imaginary part.)  @code{NA}s are sorted last.

@code{rsort_with_index} sorts on @var{x}, and applies the same
permutation to @var{index}.  @code{NA}s are sorted last.
@end deftypefun

@deftypefun void revsort (double* @var{x}, int* @var{index}, int @var{n})
Is similar to @code{rsort_with_index} but sorts into decreasing order,
and @code{NA}s are not handled.
@end deftypefun

@deftypefun void iPsort (int* @var{x}, int @var{n}, int @var{k})
@deftypefunx void rPsort (double* @var{x}, int @var{n}, int @var{k})
@deftypefunx void cPsort (Rcomplex* @var{x}, int @var{n}, int @var{k})
These all provide (very) partial sorting: they permute @var{x} so that
@code{@var{x}[@var{k}]} is in the correct place with smaller values to
the left, larger ones to the right.
@end deftypefun

@deftypefun  void R_qsort   (double *@var{v}, int @var{i}, int @var{j})
@deftypefunx void R_qsort_I (double *@var{v}, int *@var{I}, int @var{i}, int @var{j})
@deftypefunx void R_qsort_int   (int *@var{iv}, int @var{i}, int @var{j})
@deftypefunx void R_qsort_int_I (int *@var{iv}, int *@var{I}, int @var{i}, int @var{j})


These routines sort @code{@var{v}[@var{i}:@var{j}]} or
@code{@var{iv}[@var{i}:@var{j}]} (using 1-indexing, i.e.,
@code{@var{v}[1]} is the first element) calling the quicksort algorithm
as used by @R{}'s @code{sort(v, method = "quick")} and documented on the
help page for the @R{} function @code{sort}.  The @code{..._I()}
versions also return the @code{sort.index()} vector in @code{I}.  Note
that the ordering is @emph{not} stable, so tied values may be permuted.

Note that @code{NA}s are not handled (explicitly) and you should
use different sorting functions if @code{NA}s can be present.
@end deftypefun

@deftypefun subroutine qsort4 (double precision @var{v}, integer @var{indx}, integer @var{ii}, integer @var{jj})
@deftypefunx subroutine qsort3 (double precision @var{v}, integer @var{ii}, integer @var{jj})

The FORTRAN interface routines for sorting double precision vectors are
@code{qsort3} and @code{qsort4}, equivalent to @code{R_qsort} and
@code{R_qsort_I}, respectively.
@end deftypefun

@deftypefun void R_max_col (double* @var{matrix}, int* @var{nr}, int* @var{nc}, int* @var{maxes})
Given the @var{nr} by @var{ny} matrix @code{matrix} in row (``FORTRAN'')
order, @code{R_max_col()} returns in @code{@var{maxes}[@var{i}-1]} the
column number of the maximal element in the @var{i}-th row (the same as
@R{}'s @code{max.col()} function).
@end deftypefun

@deftypefun int findInterval (double* @var{xt}, int @var{n}, double @var{x}, Rboolean @var{rightmost_closed}, Rboolean @var{all_inside}, int @var{ilo}, int* @var{mflag})
Given the ordered vector @var{xt} of length @var{n}, return the interval
or index of @var{x} in @code{@var{xt}[]}, typically max(@math{i}; @eqn{1
\le i \le @var{n}, 1 <= i <= @var{n}} & @math{@var{xt}[i]} @eqn{\le, <=}
@var{x}) where we use 1-indexing as in @R{} and FORTRAN (but not C).  If
@var{rightmost_closed} is true, also returns @math{@var{n}-1} if @var{x}
equals @math{@var{xt}[@var{n}]}.  If @var{all_inside} is not 0, the
result is coerced to lie in @code{1:(@var{n}-1)} even when @var{x} is
outside the @var{xt}[] range.  On return, @code{*@var{mflag}} equals
@math{-1} if @var{x} < @var{xt}[1], @math{+1} if @var{x} >=
@var{xt}[@var{n}], and 0 otherwise.

The algorithm is particularly fast when @var{ilo} is set to the last
result of @code{findInterval()} and @var{x} is a value of a sequence which
is increasing or decreasing for subsequent calls.

There is also an @code{F77_CALL(interv)()} version of
@code{findInterval()} with the same arguments, but all pointers.
@end deftypefun

A system-independent interface to produce the name of a temporary
file is provided as

@deftypefun {char *} R_tmpnam (const char* @var{prefix})
Return a pathname for a temporary file with name beginning with
@var{prefix}.  A @code{NULL} prefix is replaced by @code{""}.
@end deftypefun

@c ----

There is also the internal function used to expand file names in several
@R{} functions, and called directly by @code{path.expand}.

@deftypefun {char *} R_ExpandFileName (char* @var{fn})
Expand a path name @var{fn} by replacing a leading tilde by the user's
home directory (if defined).  The precise meaning is platform-specific;
it will usually be taken from the environment variable @env{HOME} if
this is defined.
@end deftypefun


@node Platform and version information, Standalone Mathlib, Utility functions, The R API
@section Platform and version information
@cindex Version information from C
@findex R_Version

The header files define @code{USING_R}, which should be used to test if
the code is indeed being used with @R{}.

Header file @file{Rconfig.h} (included by @file{R.h}) is used to define
platform-specific macros that are mainly for use in other header files.
The macro @code{WORDS_BIGENDIAN} is defined on big-endian systems
(e.g.@: @code{sparc-sun-solaris2.6}) and not on little-endian systems
(such as @code{i686} under Linux or Windows). It can be useful when
manipulating binary files.

Header file @file{Rversion.h} (@strong{not} included by @file{R.h} as from
@R{} 1.6.0) defines a macro @code{R_VERSION} giving the version number
encoded as an integer, plus a macro @code{R_Version} to do the encoding.
This can be used to test if the version of @R{} is late enough, or to
include back-compatibility features.  For protection against earlier
versions of @R{} which did not have this macro, use a construction such
as

@smallexample
@group
#if defined(R_VERSION) && R_VERSION >= R_Version(0, 99, 0)
  ...
#endif
@end group
@end smallexample

More detailed information is available in the macros @code{R_MAJOR},
@code{R_MINOR}, @code{R_YEAR}, @code{R_MONTH} and @code{R_DAY}: see the
header file @file{Rversion.h} for their format.  Note that the minor
version includes the patchlevel (as in @samp{99.0}).

@node Standalone Mathlib,  , Platform and version information, The R API
@section Using these functions in your own C code

It is possible to build @code{Mathlib}, the @R{} set of mathematical
functions documented in @file{Rmath.h}, as a standalone library
@file{libRmath} under Unix and Windows.  (This includes the functions
documented in @ref{Numerical analysis subroutines} as from that header file.)

The library is not built automatically when @R{} is installed, but can
be built in the directory @file{src/nmath/standalone}. See the file
@file{README} there.  To use the code in your own C program include

@smallexample
@group
#define MATHLIB_STANDALONE
#include <Rmath.h>
@end group
@end smallexample

@noindent
and link against @samp{-lRmath}.  There is an example file
@file{test.c}.

A little care is needed to use the random-number routines. You will
need to supply the uniform random number generator

@smallexample
double unif_rand(void)
@end smallexample

@noindent
or use the one supplied (and with a shared library or DLL you will have
to use the one supplied, which is the Marsaglia-multicarry with an entry
point

@smallexample
set_seed(unsigned int, unsigned int)
@end smallexample

@noindent
to set its seeds).

@node Generic functions and methods, R (internal) programming miscellanea, The R API, Top
@chapter Generic functions and methods
@cindex Generic functions
@cindex Method functions

@R{} programmers will often want to add methods for existing generic
functions, and may want to add new generic functions or make existing
functions generic.  In this chapter we give guidelines for doing so,
with examples of the problems caused by not adhering to them.

This chapter only covers the `informal' class system copied from S3,
and not with the formal methods of package @pkg{methods} of @R{} 1.4.0
and later.

The key function for methods is @code{NextMethod}, which dispatches the
next method.  It is quite typical for a method function to make a few
changes to its arguments, dispatch to the next method, receive the
results and modify them a little.  An example is

@smallexample
@group
t.data.frame <- function(x)
@{
    x <- as.matrix(x)
    NextMethod("t")
@}
@end group
@end smallexample

@noindent
Also consider @code{predict.glm}: it happens that in @R{} for historical
reasons it calls @code{predict.lm} directly, but in principle (and in S
originally and currently) it could use @code{NextMethod}.
(@code{NextMethod} seems under-used in the @R{} sources.)

@emph{Any} method a programmer writes may be invoked from another method
by @code{NextMethod}, @emph{with the arguments appropriate to the
previous method}.  Further, the programmer cannot predict which method
@code{NextMethod} will pick (it might be one not yet dreamt of), and the
end user calling the generic needs to be able to pass arguments to the
next method.  For this to work

@quotation
@emph{A method must have all the arguments of the generic, including
@code{@dots{}} if the generic does.}
@end quotation

It is a grave misunderstanding to think that a method needs only to
accept the arguments it needs.  The original S version of
@code{predict.lm} did not have a @code{@dots{}} argument, although
@code{predict} did.  It soon became clear that @code{predict.glm} needed
an argument @code{dispersion} to handle over-dispersion.  As
@code{predict.lm} had neither a @code{dispersion} nor a @code{@dots{}}
argument, @code{NextMethod} could no longer be used.  (The legacy, two
direct calls to @code{predict.lm}, lives on in @code{predict.glm} in
@R{}, which is based on the workaround for S3 written by Venables &
Ripley.)

Further, the user is entitled to use positional matching when calling
the generic, and the arguments to a method called by @code{UseMethod}
are those of the call to the generic.  Thus

@quotation
@emph{A method must have arguments in exactly the same order as the
generic.}
@end quotation

@noindent
To see the scale of this problem, consider the generic function
@code{scale}, defined (in @R{} 1.4.0) as

@smallexample
@group
scale <- function (x, center = TRUE, scale = TRUE)
    UseMethod("scale")
@end group
@end smallexample

@noindent
Suppose an unthinking package writer created methods such as

@smallexample
scale.foo <- function(x, scale = FALSE, ...) @{ @}
@end smallexample

@noindent
Then for @code{x} of class @code{"foo"} the calls

@smallexample
@group
scale(x, , TRUE)
scale(x, scale = TRUE)
@end group
@end smallexample

@noindent
would do most likely do different things, to the justifiable
consternation of the end user.

To add a further twist, which default is used when a user calls
@code{scale(x)} in our example?  What if

@smallexample
scale.bar <- function(x, center, scale = TRUE) NextMethod("scale")
@end smallexample

@noindent
and @code{x} has class @code{c("bar", "foo")}?  We are not going to give
you the answers because it is unreasonable that a user should be
expected to anticipate such behaviour.  This leads to the
recommendation:

@quotation
@emph{A method should use the same defaults as the generic.}
@end quotation

@noindent
Here there might be justifiable exceptions, which will need careful
documentation.

@menu
* Adding new generics::
@end menu

@node Adding new generics,  , Generic functions and methods, Generic functions and methods
@section Adding new generics

When creating a new generic function, bear in mind that its argument
list will be the maximal set of arguments for methods, including those
written elsewhere years later.  So choosing a good set of arguments may
well be an important design issue, and there need to be good arguments
@emph{not} to include a @code{@dots{}} argument.

If a @code{@dots{}} argument is supplied, some thought should be given
to its position in the argument sequence.  Arguments which follow
@code{@dots{}} must be named in calls to the function, and they must be
named in full (partial matching is suppressed after @code{@dots{}}).
Formal arguments before @code{@dots{}} can be partially matched, and so
may `swallow' actual arguments intended for @code{@dots{}}.  Although it
is commonplace to make the @code{@dots{}} argument the last one, that is
not always the right choice.

Sometimes package writers want to make generic a function in the base
package, and request a change in @R{}.  This may be justifiable, but
making a function generic with the old definition as the default method
does have a small performance cost.  It is never necessary, as a package
can take over a function in the base package and make it generic by

@smallexample
@group
foo <- function(object, ...) UseMethod("foo")
foo.default <- get("foo", pos = NULL, mode = "function")
@end group
@end smallexample

@noindent
(If the thus defined default method needs a @samp{...} added to its
argument list, one can e.g.@: use @code{formals(foo.default) <-
c(formals(foo.default), alist(... = ))}.)

Note that this cannot be used for functions in another package, as the
order of packages on the search path cannot be controlled, except that
all precede the base package.  Where the name of the package is known
and it is in a namespace another way to access the orignal form is

@smallexample
foo.default <- base::foo
@end smallexample


@node R (internal) programming miscellanea, R coding standards, Generic functions and methods, Top
@appendix R (internal) programming miscellanea

@menu
* .Internal and .Primitive::
* Testing R code::
@end menu

@node .Internal and .Primitive, Testing R code, R (internal) programming miscellanea, R (internal) programming miscellanea
@section @code{.Internal} and @code{.Primitive}

@findex .Internal
@findex .Primitive

C code compiled into @R{} at build time can be called ``directly'' or
via the @code{.Internal} interface, which is very similar to the
@code{.External} interface except in syntax.  More precisely, @R{}
maintains a table of R function names and corresponding C functions to
call, which by convention all start with @samp{do_} and return a SEXP.
Via this table (@code{R_FunTab} in file @file{src/main/names.c}) one can
also specify how many arguments to a function are required or allowed,
whether the arguments are to be evaluated before calling or not, and
whether the function is ``internal'' in the sense that it must be
accessed via the @code{.Internal} interface, or directly accessible in
which case it is printed in @R{} as @code{.Primitive}.

@R{}'s functionality can also be extended by providing corresponding C
code and adding to this function table.

In general, all such functions use @code{.Internal()} as this is safer
and in particular allows for transparent handling of named and default
arguments.  For example, @code{axis} is defined as

@smallexample
@group
axis <- function(side, at = NULL, labels = NULL, ...)
    .Internal(axis(side, at, labels, ...))
@end group
@end smallexample

However, for reasons of convenience and also efficiency (as there is
some overhead in using the @code{.Internal} interface), there are
exceptions which can be accessed directly.  Note that these functions
make no use of @R{} code, and hence are very different from the usual
interpreted functions.  In particular, @code{args} and @code{body}
return @code{NULL} for such objects.

The list of these ``primitive'' functions is subject to change:
currently, it includes the following.

@enumerate

@item
``Special functions'' which really are @emph{language} elements, however
exist as ``primitive'' functions in @R{}:

@smallexample
@group
@{       (         if     for      while  repeat  break  next
return  function  quote  on.exit
@end group
@end smallexample

@item
Basic @emph{operator}s (i.e., functions usually @emph{not} called as
@code{foo(a, b, ...)}) for subsetting, assignment, arithmetic and logic.
These are the following 1-, 2-, and @math{N}-argument functions:

@smallexample
@group
          [    [[    $
<-   <<-  [<-  [[<-  $<-

+    -    *    /     ^    %%   %*%  %/%
<    <=   ==   !=    >=   >
|    ||   &    &&    !
@end group
@end smallexample

@item
``Low level'' 0- and 1-argument functions which belong to one of the
following groups of functions:

@enumerate a
@item
Basic mathematical functions with a single argument, i.e.,

@smallexample
@group
sign    abs
floor   ceiling  trunc
@end group

@group
sqrt    exp
cos     sin      tan
acos    asin     atan
cosh    sinh     tanh
acosh   asinh    atanh
@end group

@group
cumsum  cumprod
cummax  cummin
@end group

@group
Im      Re
Arg     Conj     Mod
@end group
@end smallexample

@noindent Note however that the @R{} function @code{log} has an optional
named argument @code{base}, and therefore is defined as

@smallexample
@group
log <- function(x, base = exp(1)) @{
  if(missing(base))
    .Internal(log(x))
  else
    .Internal(log(x, base))
@}
@end group
@end smallexample

@noindent in order to ensure that @code{log(x = pi, base = 2)} is
identical to @code{log(base = 2, x = pi)}.

@item
Functions rarely used outside of ``programming'' (i.e., mostly used
inside other functions), such as

@smallexample
@group
nargs        missing
interactive  is.@emph{xxx}
.Primitive   .Internal   .External
symbol.C     symbol.For
globalenv    pos.to.env  unclass
@end group
@end smallexample

@noindent
(where @emph{xxx} stands for almost 30 different notions, such as
@code{function}, @code{vector}, @code{numeric}, and so forth).

@item
The programming and session management utilities

@smallexample
@group
debug    undebug    trace  untrace
browser  proc.time
@end group
@end smallexample

@end enumerate

@item
The following basic assignment and extractor functions

@smallexample
@group
length      length<-
class       class<-
attr        attr<-
attributes  attributes<-
dim         dim<-
dimnames    dimnames<-
            environment<-
@end group
@end smallexample

@item
The following few @math{N}-argument functions are ``primitive'' for
efficiency reasons.  Care is taken in order to treat named arguments
properly:

@smallexample
@group
:          ~          c           list        unlist
call       as.call    expression  substitute
UseMethod  invisible
.C         .Fortran   .Call
@end group
@end smallexample

@end enumerate

@node Testing R code,  , .Internal and .Primitive, R (internal) programming miscellanea
@section Testing R code

When you (as @R{} developer) add new functions to the R base (all the
packages distributed with @R{}), be careful to check if @kbd{make
test-Specific} or particularly, @kbd{cd tests; make no-segfault.Rout}
still works (without interactive user intervention, and on a standalone
computer).  If the new function, for example, accesses the Internet, or
requires @acronym{GUI} interaction, please add its name to the ``stop
list'' in @file{tests/no-segfault.Rin}.

@node R coding standards, Function and variable index, R (internal) programming miscellanea, Top
@appendix R coding standards

@R{} is meant to run on a wide variety of platforms, including Linux and
most variants of Unix as well as 32-bit Windows versions and on the
Power Mac.  Therefore, when extending @R{} by either adding to the @R{}
base distribution or by providing an add-on package, one should not rely
on features specific to only a few supported platforms, if this can be
avoided.  In particular, although most @R{} developers use @acronym{GNU}
tools, they should not employ the @acronym{GNU} extensions to standard
tools.  Whereas some other software packages explicitly rely on e.g.@:
@acronym{GNU} make or the @acronym{GNU} C++ compiler, @R{} does not.
Nevertheless, @R{} is a @acronym{GNU} project, and the spirit of the
@cite{@acronym{GNU} Coding Standards} should be followed if possible.

The following tools can ``safely be assumed'' for @R{} extensions.

@itemize @bullet
@item
An ISO 9899, also known as ISO C89 or @acronym{ANSI} C compiler.  If you
do not have access to this C standard, refer to the 2nd edition of Brian
W. Kernighan & Dennis M. Ritchie, @cite{The C Programming Language}.
Any extensions, such as @acronym{POSIX} or ISO C99, must be tested for,
typically using Autoconf (@pxref{Configure and cleanup}).

@item
A FORTRAN 77 compiler or @command{f2c}, the FORTRAN-to-C converter.

@item
A simple @command{make}, considering the features of @command{make} in
4.2 @acronym{BSD} systems as a baseline.

@acronym{GNU} or other extensions, including pattern rules using
@samp{%}, the automatic variable @samp{$^}, the @samp{+=} syntax to
append to the value of a variable, the (``safe'') inclusion of makefiles
with no error, conditional execution, and many more, must not be used
(see Chapter ``Features'' in the @cite{@acronym{GNU} Make Manual} for
more information).  On the other hand, building @R{} in a separate
directory (not containing the sources) should work provided that
@command{make} supports the @code{VPATH} mechanism.

Windows-specific makefiles can assume @acronym{GNU} @command{make} 3.75
or later, as no other @command{make} is viable on that platform.

@item
A Bourne shell and the ``traditional'' Unix programming tools, including
@command{grep}, @command{sed}, and @command{awk}.

There are @acronym{POSIX} standards for these tools, but these may not
fully be supported, and the precise standards are typically hard to
access.  Baseline features could be determined from a book such as
@cite{The UNIX Programming Environment} by Brian W. Kernighan & Rob
Pike.  Note in particular that @samp{|} in a regexp is an extended
regexp, and is not supported by all versions of @command{grep} or
@command{sed}.

Under Windows, these tools can be assumed because versions
(specifically, of @command{basename}, @command{cat}, @command{comm},
@command{cp}, @command{cut}, @command{diff}, @command{echo},
@command{egrep}, @command{expr}, @command{find}, @command{gawk},
@command{grep}, @command{ls}, @command{mkdir}, @command{mv},
@command{rm}, @command{sed}, @command{sort}, @command{tar},
@command{touch}, @command{unzip}, @command{wc} and @command{zip}) are
provided at @url{http://www.stats.ox.ac.uk/pub/Rtools/tools.zip}.  However,
redirection cannot be assumed to be available via @command{system} as
this does not use a standard shell (let alone a Bourne shell).
@end itemize

@noindent
In addition, the following tools are needed for certain tasks.

@itemize @bullet
@item
Perl version 5 is needed for converting documentation written in Rd
format to plain text, @HTML{}, La@TeX{}, and to extract the examples.
In addition, several other tools, in particular @command{check} and
@command{build} (@pxref{Checking and building packages}), require Perl.

The @R{} Core Team has decided that Perl (version 5) can safely be
assumed for building @R{} from source, building and checking add-on
packages, and for installing add-on packages from source.  On the other
hand, Perl cannot be assumed at all for installing @emph{binary}
(pre-built) versions of add-on packages, or at run time.

@item
Makeinfo version 4 is needed to build the Info files for the @R{}
manuals written in the @acronym{GNU} Texinfo system.  (Future
distributions of @R{} will contain the Info files.)
@end itemize

It is also important that code is written in a way that allows others to
understand it.  This is particularly helpful for fixing problems, and
includes using self-descriptive variable names, commenting the code, and
also formatting it properly.  The @R{} Core Team recommends to use a
basic indentation of 4 for @R{} and C (and most likely also Perl) code,
and 2 for documentation in Rd format.  Emacs users can implement this
indentation style by putting the following in one of their startup
files.  (For @acronym{GNU} Emacs 20: for @acronym{GNU} Emacs 21 use
customization to set the @code{c-default-style} to @code{"bsd"} and
@code{c-basic-offset} to @code{4}.)

@smallexample
@group
;;; C
(add-hook 'c-mode-hook
          (lambda () (c-set-style "bsd")))
@end group
@group
;;; ESS
(add-hook 'ess-mode-hook
          (lambda ()
            (ess-set-style 'C++)
            ;; Because
            ;;                                 DEF GNU BSD K&R C++
            ;; ess-indent-level                  2   2   8   5   4
            ;; ess-continued-statement-offset    2   2   8   5   4
            ;; ess-brace-offset                  0   0  -8  -5  -4
            ;; ess-arg-function-offset           2   4   0   0   0
            ;; ess-expression-offset             4   2   8   5   4
            ;; ess-else-offset                   0   0   0   0   0
            ;; ess-close-brace-offset            0   0   0   0   0
            (add-hook 'local-write-file-hooks
                      (lambda ()
                        (nuke-trailing-whitespace)))))
@end group
@group
;;; Perl
(add-hook 'perl-mode-hook
          (lambda () (setq perl-indent-level 4)))
@end group
@end smallexample

@noindent
(The `GNU' styles for Emacs' C and R modes use a basic indentation of 2,
which has been determined not to display the structure clearly enough
when using narrow fonts.)


@node Function and variable index, Concept index, R coding standards, Top
@unnumbered Function and variable index

@printindex vr

@node Concept index,  , Function and variable index, Top
@unnumbered Concept index

@printindex cp

@bye

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