Writing R Extensions Guide
Writing R Extensions Guide
Table of Contents
Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1 Creating R packages . . . . . . . . . . . . . . . . . . . . . . . 2
1.1 Package structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.1.1 The ‘DESCRIPTION’ file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.1.2 The ‘INDEX’ file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.3 Package subdirectories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.1.4 Package bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2 Configure and cleanup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.2.1 Using ‘Makevars’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.3 Checking and building packages . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.4 Writing package vignettes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.5 Submitting a package to cran . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.6 Package name spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Concept index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
1
Acknowledgements
The contributions of Saikat DebRoy (who wrote the first draft of a guide to using .Call
and .External) and of Adrian Trapletti (who provided information on the C++ interface)
are gratefully acknowledged.
Chapter 1: Creating R packages 2
1 Creating R packages
Packages provide a mechanism for loading optional code and attached documentation as
needed. The R distribution provides several packages, such as eda, mva, and stepfun.
In the following, we assume that you know the ‘library()’ command, including its
‘[Link]’ argument, and we also assume basic knowledge of R CMD INSTALL. Otherwise,
please look at R’s help pages
?library
?INSTALL
before reading on. If the package you are writing uses the methods package, look at the
corresponding section in ?INSTALL.
Once a source package is created, it must be installed. Under Unix-alikes that is
done by R CMD INSTALL. Under Windows, Rcmd INSTALL is used, but please see the file
‘[Link]’ (in the top-level directory of the binary installation) for the tools that
you need to have installed.
The ‘DESCRIPTION’ file contains basic information about the package in the following format:
Chapter 1: Creating R packages 3
Package: pkgname
Version: 0.5-1
Date: 2000-01-04
Title: My first collection of functions
Author: Friedrich Leisch <[Link]@[Link]>, with
contributions from A. User <[Link]@[Link]>.
Maintainer: Friedrich Leisch <[Link]@[Link]>
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: [Link] [Link]
Continuation lines (for example, for descriptions longer than one line) start with a space
or tab. The ‘Package’, ‘Version’, ‘License’, ‘Description’, ‘Title’, ‘Author’, and
‘Maintainer’ fields are mandatory, the remaining fields (‘Date’, ‘Depends’, ‘URL’, . . . ) are
optional.
The ‘Package’ and ‘Version’ fields give the name and the version of the package, re-
spectively. The name should consist of letters, numbers, and the dot character and start
with a letter. The version is a sequence of at least two non-negative integers separated by
single ‘.’ or ‘-’ characters.
The ‘License’ field should contain an explicit statement or a well-known abbreviation
(such as ‘GPL’, ‘LGPL’, ‘BSD’, or ‘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 ‘Description’ field should give a comprehensive description of what the package
does. One can use several (complete) sentences, but only one paragraph.
The ‘Title’ field should give a short description of the package. It should be capitalized,
not use any markup, not have any continuation lines, and not end in a period. Older versions
of R used a separate file ‘TITLE’ for giving this information; this is now defunct, and the
‘Title’ field in ‘DESCRIPTION’ is required.
The ‘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 ‘Maintainer’ field should give a single name with email address in angle brackets
(for sending bug reports etc.). It should not end in a period or comma.
The optional ‘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 ‘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 op-
erator (currently only ‘>=’ and ‘<=’ 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 ‘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 ‘R (>= 0.90)’ in the ‘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 ‘Depends’ field for comments on other software
that might be needed. Other dependencies (external to the R system) should be listed in
Chapter 1: Creating R packages 4
the ‘SystemRequirements’ field or a separate ‘README’ file. The R INSTALL facilities already
check if the version of R used is recent enough for the package being installed.
The optional ‘URL’ field may give a list of urls 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 urls are converted to active hyperlinks on cran.
Base and recommended packages (i.e., packages contained in the R source distribution
or available from cran and recommended to be included in every binary distribution of R)
have a ‘Priority’ field with value ‘base’ or ‘recommended’, respectively. These priorities
must not be used by “other” packages.
An optional ‘Collate’ field (or OS-specific variants ‘[Link] ’, such as e.g.
‘[Link]’) can be used for controlling the collation order for the R code files
in a package when these are concatenated into a single file upon installation from source.
The default is to try collating according to the ‘C’ locale. If present, the collate specifica-
tion must list all R code files in the package (taking possible OS-specific subdirectories into
account, see Section 1.1.3 [Package subdirectories], page 4) as a whitespace separated list of
file paths relative to the ‘R’ subdirectory. Paths containing white space or single or double
quotes need to be quoted. Applicable OS-specific collate specifications take precedence.
The optional file ‘INDEX’ contains a line for each sufficiently interesting object in the pack-
age, 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 Rdindex() from package
tools) when installing from source and when using the package builder (see Section 1.3
[Checking and building packages], page 9).
The ‘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 ‘.R’, ‘.S’, ‘.q’, ‘.r’, or ‘.s’.
We recommend using ‘.R’, as this extension seems to be not used by any other software.
It should be possible to read in the files using 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 ‘zzz.R’) should use
[Link]() inside .[Link]() to load compiled code.
The ‘man’ subdirectory should contain documentation files for the objects in the package
in R documentation (Rd) format. The documentation files to be installed must also start
with a (lower or upper case) letter and have the extension ‘.Rd’ (the default) or ‘.rd’. See
Chapter 2 [Writing R documentation files], page 16, for more information. Note that all
user-level objects in a package should be documented; if a package pkg contains user-level
objects which are for “internal” use only, it should provide a file ‘[Link]’ 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 tools in the R distribution for an example.
The ‘R’ and ‘man’ subdirectories may contain OS-specific subdirectories named ‘unix’ or
‘windows’.
Chapter 1: Creating R packages 5
The C, C++, or FORTRAN1 source files for the compiled code are in ‘src’, plus op-
tionally file ‘Makevars’ or ‘Makefile’. When a package is installed using R CMD INSTALL,
Make is used to control compilation and linking into a shared object for loading into
R. There are default variables and rules for this (determined when R is configured and
recorded in ‘R_HOME /etc/Makeconf’). These rules can be tweaked by setting macros in a
file ‘src/Makevars’ (see Section 1.2.1 [Using Makevars], page 8). Note that this mechanism
should be general enough to eliminate the need for a package-specific ‘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 ‘clean’ which removes all files generated
by Make. If necessary, platform-specific files can be used, for example ‘[Link]’ or
‘[Link]’ on Windows take precedence over ‘Makevars’ or ‘Makefile’.
The ‘data’ subdirectory is for additional data files the package makes available for load-
ing using data(). Currently, data files can have one of three types as indicated by their
extension: plain R code (‘.R’ or ‘.r’), tables (‘.tab’, ‘.txt’, or ‘.csv’), or save() images
(‘.RData’ or ‘.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 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 ‘00Index’ file in the ‘data’ directory—the corresponding information is generated
automatically from the documentation sources when installing from source, or when using
the package builder (see Section 1.3 [Checking and building packages], page 9).
The ‘demo’ subdirectory is for R scripts (for running via 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 ‘.R’ or ‘.r’. If present, the ‘demo’ subdirectory should
also have a ‘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 ‘inst’ subdirectory will be copied recursively to the installation
directory. Subdirectories of ‘inst’ should not interfere with those used by R (currently,
‘R’, ‘data’, ‘demo’, ‘exec’, ‘man’, ‘help’, ‘html’, ‘latex’, and ‘R-ex’). As from R 1.8.1 the
copying of the ‘inst’ happens after ‘src’ is built so its ‘Makefile’ can create files to be
installed.
Subdirectory ‘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
‘.R’ file, or via a ‘.Rin’ file containing code which in turn creates the corresponding ‘.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 ‘.R’ file are written to a ‘.Rout’ file. If
there is a corresponding ‘.[Link]’ file, these two are compared, with differences being
reported but not causing an error.
Finally, ‘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.
1
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.
Chapter 1: Creating R packages 6
The ‘Contains’ field lists the packages, which should be contained in separate subdi-
rectories with the names given. These are standard packages in all respects except that
the ‘DESCRIPTION’ file is replaced by a ‘[Link]’ file which just contains fields
additional to the ‘DESCRIPTION’ file of the bundle, for example
Package: spatial
Description: Functions for kriging and point pattern analysis.
Note that most of this section is Unix-specific: see the comments later on about the Windows
port of R.
If your package needs some system-dependent configuration before installation you can
include a (Bourne shell) script ‘configure’ in your package which (if present) is executed
by 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 ‘cleanup’ is executed as last thing by R CMD INSTALL if present
and option ‘--clean’ was given, and by R CMD build when preparing the package for build-
ing from its source. It can be used to clean up the package source tree. In particular, it
should remove all files created by configure.
As an example consider we want to use functionality provided by a (C or FORTRAN)
library foo. Using autoconf, we can create a configure script which checks for the library,
sets variable HAVE_FOO to TRUE if it was found and with FALSE otherwise, and then substi-
tutes this value into output files (by replacing instances of ‘@HAVE_FOO@’ in input files with
Chapter 1: Creating R packages 7
the value of HAVE_FOO). For example, if a function named bar is to be made available by
linking against library foo (i.e., using ‘-lfoo’), one could use
AC_CHECK_LIB(foo, fun, [HAVE_FOO=TRUE], [HAVE_FOO=FALSE])
AC_SUBST(HAVE_FOO)
......
AC_CONFIG_FILES([foo.R])
AC_OUTPUT
in ‘[Link]’ (assuming Autoconf 2.50 or better).
The definition of the respective R function in ‘[Link]’ could be
foo <- function(x) {
if(!@HAVE_FOO@) stop("Sorry, library ‘foo’ is not available")
...
From this file configure creates the actual R source file ‘foo.R’ looking like
foo <- function(x) {
if(!FALSE) stop("Sorry, library ‘foo’ is not available")
...
if library 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, respec-
tively.
You will very likely need to ensure that the same C compiler and compiler flags are used
in the ‘configure’ tests as when compiling R or your package. Under Unix, you can achieve
this by including the following fragment early in ‘[Link]’
: ${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‘
(using ‘${R_HOME}/bin/R’ rather than just ‘R’ is necessary in order to use the ‘right’ version
of R when running the script as part of R CMD INSTALL.)
Note that earlier versions of this document recommended obtaining the configure infor-
mation by direct extraction (using grep and sed) from ‘R_HOME /etc/Makeconf’, which only
works for variables recorded there as literals. R 1.5.0 has added R CMD config for getting
the value of the basic configuration variables, or the header and library flags necessary for
linking against R, see R CMD config --help for details.
If R was configured to use the FORTRAN-to-C converter (f2c), configure variable 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 ACX_BLAS macro from the Official Autoconf Macro Archive, one
can simply do
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))
Note that FLIBS as determined by R must be used to ensure that FORTRAN 77 code
works on all R platforms. Calls to the Autoconf macro AC_F77_LIBRARY_LDFLAGS, which
Chapter 1: Creating R packages 8
would overwrite FLIBS, must not be used (and hence e.g. removed from ACX_BLAS). (Recent
versions of Autoconf in fact allow an already set FLIBS to override the test for the Fortran
linker flags. Also, recent versions of R can detect external BLAS and LAPACK libraries.)
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 ‘[Link]’ script to be used on that platform.
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 object/DLLs. Usually, the object that is dynamically
loaded by R is linked against the second, dependent, object. On some systems, we can
add the location of this dependent object to the object that is dynamically loaded by R.
This means that each user does not have to set the value of the LD_LIBRARY_PATH (or
equivalent) environment variable, but that the secondary object 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 SJava package.)
The names of the top-level library directory (i.e., specifiable via the ‘-l’ argument) and
the directory of the package itself are made available to the installation scripts via the two
shell/environment variables R_LIBRARY_DIR and R_PACKAGE_DIR. Additionally, the name
of the package (e.g., ‘survival’ or ‘MASS’) being installed is available from the shell variable
R_PACKAGE_NAME.
Sometimes writing your own ‘configure’ script can be avoided by supplying a file
‘Makevars’: also one of the commonest uses of a ‘configure’ script is to make ‘Makevars’
from ‘[Link]’.
The most common use of a ‘Makevars’ file is to set additional compiler flags (for example
include paths) by setting PKG_CFLAGS, PKG_CXXFLAGS and PKG_FFLAGS, for C, C++, or
FORTRAN respectively (see Section 4.5 [Creating shared objects], page 35).
Also, ‘Makevars’ can be used to set flags for the linker, for example ‘-L’ and ‘-l’ options.
There are some macros which are built whilst configuring the building of R itself, are
stored in ‘R_HOME /etc/Makeconf’ and can be used in ‘Makevars’. These include
FLIBS A macro containing the set of libraries need to link FORTRAN code. This may
need to be included in PKG_LIBS.
BLAS_LIBS
A macro containing the BLAS libraries used when building R. This may need
to be included in 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.
LAPACK_LIBS
A macro containing the LAPACK libraries (and paths where appropriate) used
when building R. This may need to be included in PKG_LIBS. This may point to
Chapter 1: Creating R packages 9
Using R CMD check, the R package checker, one can test whether source R packages work
correctly. (Under Windows the equivalent command is Rcmd check.) This runs a series of
checks.
1. The package is installed. This will warn about missing cross-references and duplicate
aliases in help files.
2. The file names are checked to be valid across file systems and supported operating
system platforms.
3. The files and directories are checked for sufficient permissions (Unix only).
4. The ‘DESCRIPTION’ file is checked for completeness, and some of its entries for correct-
ness. Unless installation tests are skipped, checking is aborted if the package depen-
dencies cannot be resolved at run time.
5. Available index information (in particular, for demos and vignettes) is checked for
completeness.
6. The R files are checked for syntax errors.
7. The R files are checked for correct calls to [Link] (with no extension). In ad-
dition, it is checked whether methods have all arguments of the corresponding generic,
and whether the final argument of replacement functions is called ‘value’.
8. The Rd files are checked for the mandatory (\name, \alias, \title, \description
and \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.
9. A check is made for missing documentation entries, such as undocumented user-level
objects in the package
10. The functions and their documentation are compared, and any differences in the call
sequences reported.
11. It is checked whether all function arguments given in \usage sections of Rd files are
documented in the corresponding \arguments section.
12. C source and header files are tested for correct (LF-only) line endings.
13. The examples provided by the package’s documentation are run. (see Chapter 2 [Writ-
ing R documentation files], page 16, for information on using \examples to create
executable example code.)
Of course, released packages should be able to run at least their own examples.
Chapter 1: Creating R packages 10
14. If the package sources contain a ‘tests’ directory then the tests specified in that direc-
tory are run. (Typically they will consist of a set of ‘.R’ source files and target output
files ‘.[Link]’.)
15. The code in package vignettes (see Section 1.4 [Writing package vignettes], page 10) is
executed.
16. If a working latex program is available, the ‘.dvi’ version of the package’s manual is
created (to check that the Rd files can be converted successfully).
Use R CMD check --help (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.
Using R CMD build, the R package builder, one can build R packages from their sources
(for example, for subsequent release). The Windows equivalent is 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
‘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 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 ‘.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 ‘CVS’ or ‘GNUMakefile’, or with base names starting with
‘.#’, or starting and ending with ‘#’, or ending in ‘~’ or ‘.bak’ or ‘.swp’, are excluded by
default.
Note: file exclusion does not work correctly with gnu tar 1.13 but does work
with later versions (e.g., version 1.13.17).
Use R CMD build --help (Rcmd build --help on Windows) to obtain more information
about the usage of the R package builder.
R CMD build can also build pre-compiled version of packages for binary distributions.
Note: R CMD check and R CMD build run R with ‘--vanilla’, so none of the
user’s startup files are read. If you need R_LIBS set (to find packages in a
non-standard library) you will need to set it in the environment.
Note to Windows users: Rcmd check and Rcmd build work well under Windows
NT4/2000/XP but may not work correctly on Windows 95/98/ME because of
problems with some versions of Perl on those limited OSes. Experiences vary.
To use them you will need to have installed the files for building source packages.
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 ‘inst/doc’ of
a source package, the contents will be copied to subdirectory ‘doc’ when the package is
installed. Pointers from package help indices to the installed documents are automatically
Chapter 1: Creating R packages 11
cran is a network of WWW sites holding the R distributions and contributed code, espe-
cially R packages. Users of R are encouraged to join in the collaborative project and to
submit their own packages to cran.
Chapter 1: Creating R packages 12
Before submitting a package mypkg, do run the following steps to test it is complete and
will install properly. (Unix procedures only, run from the directory containing ‘mypkg’ as a
subdirectory.)
1. Run 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. ‘-Wall -pedantic’ for tools from GCC, the
Gnu Compiler Collection. (If R was not configured accordingly, one can achieve this
e.g. via PKG_CFLAGS and related variables.)
2. Run R CMD build to run a few further checks and to make the release ‘.[Link]’ file.
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 ‘.[Link]’ file to
[Link]
and send a message to cran@[Link] about it. The 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 ‘.[Link]’ file must be of the form
‘package _version [_engine [_type ]]’,
where the ‘[ ]’ indicates that the enclosed component is optional, package and version are
the corresponding entries in file ‘DESCRIPTION’, engine gives the S engine the package is
targeted for and defaults to ‘R’, and type indicated whether the file contains source or
binaries for a certain platform, and defaults to ‘source’. I.e.,
OOP_0.[Link]
OOP_0.1-3_R.[Link]
OOP_0.1-3_R_source.[Link]
are all equivalent and indicate an R source package, whereas
OOP_0.1-3_Splus6_sparc-[Link]
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 ‘.[Link]’ files can only be assumed to work provided
that this naming scheme is respected. Of course, R CMD build automatically creates valid
file names.
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 exported
to make them available to package users, and which variables should be imported from other
packages.
The current mechanism2 for specifying a name space for a package is to place a
‘NAMESPACE’ file in the top level package directory. This file contains name space directives
2
Alternate approaches are under consideration and may replace this approach in future R releases.
Chapter 1: Creating R packages 13
describing the imports and exports of the name space. Additional directives register any
shared objects 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 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 not be placed on
the search path by these implicit loads.
Exports are specified using the export directive. A directive of the form
export(f, g)
specifies that the variables f and g are to be exported. (Note that variable names may be
quoted, and non-standard names such as [<-.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 exportPattern. The directive
exportPattern("^[^\\.]")
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 import and importFrom. The import directive
imports all exported variables from the specified package(s). Thus the directives
import(foo, bar)
specifies that all exported variables in the packages foo and bar are to be imported. If
only some of the variables from a package are needed, then they can be imported using
importFrom. The directive
importFrom(foo, f, g)
specifies that the exported variables f and g of the package 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 f in package foo is of the form foo::f. This is less efficient than a formal
import and also loses the advantage of recording all dependencies in the ‘NAMESPACE’ file,
so this approach is usually not recommended. Evaluating foo::f will cause package foo to
be loaded, but not attached, if it was not loaded already.
The standard method for S3-style 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 S3method directives. If a package
defines a function [Link] intended to be used as a print method for class foo, then
the directive
S3method(print, foo)
ensures that the method is registered and available for UseMethod dispatch. The function
[Link] does not need to be exported. Since the generic print is defined in 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.
Chapter 1: Creating R packages 14
Packages with name spaces do not use the .[Link] 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 .onLoad and .onAttach. They take the same
arguments as .[Link]; they should be defined in the package but not exported. Packages
are not likely to need .onAttach; code to set options and load shared objects should be
placed in a .onLoad function, or use made of the useDynLib directive described next.
The useDynLib directive allows shared objects that need to be loaded to be specified in
the ‘NAMESPACE’ file. The directive
useDynLib(foo)
registers the shared object foo for loading with [Link]. Loading of registered
objects 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 object can
use the useDynLib directive instead.
As an example consider two packages named foo and bar. The R code for package foo
in file ‘foo.R’ is
x <- 1
f <- function(y) c(x,y)
foo <- function(x) .Call("foo", x, PACKAGE="foo")
[Link] <- function(x, ...) cat("<a foo>\n")
Some C code defines a C function compiled into DLL foo (with an appropriate extension).
The ‘NAMESPACE’ file for this package is
useDynLib(foo)
export(f, foo)
S3method(print, foo)
Calling library(bar) loads bar and attaches its exports to the search path. Package foo
is also loaded but not attached to the search path. A call to g produces
> g(6)
[1] 1 13
This is consistent with the definitions of c in the two settings: in bar the function c is
defined to be equivalent to sum, but in foo the variable c refers to the standard function c
in base.
Chapter 1: Creating R packages 15
To summarize, converting an existing package to use a name space involves several simple
steps:
• Identify the public definitions and place them in export directives.
• Identify S3-style method definitions and write corresponding S3method declarations.
• Identify dependencies and replace any require calls by import directives.
• Replace .[Link] functions with .onLoad functions or useDynLib directives.
Some code analysis tools to aid in this process are currently under development.
Name spaces are 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
methods package. Support for methods is anticipated for the following release of R.
Chapter 2: Writing R documentation files 16
2.1 Rd format
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.
Chapter 2: Writing R documentation files 17
See the “Guidelines for Rd files” for guidelines for writing documentation in Rd format
which should be useful for package writers.
The basic markup commands used for documenting R objects (in particular, functions) are
given in this subsection.
\name{name }
name typically is the basename of the Rd file containing the documentation.
It is the “name” of the Rd object represented by the file, has to be unique in
a package, and must not contain LaTEX special characters (‘#’, ‘$’, ‘%’, ‘&’, ‘~’,
‘_’, ‘^’, ‘\’, ‘{’, ‘}’).
\alias{topic }
The \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 \alias entries. Quite often it is convenient to document
several R objects in one file. For example, file ‘[Link]’ documents the den-
sity, distribution function, quantile function and generation of random variates
for the normal distribution, and hence starts with
\name{Normal}
\alias{dnorm}
\alias{pnorm}
\alias{qnorm}
\alias{rnorm}
Note that the \name is not necessarily a topic documented.
\title{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).
\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.)
\usage{fun (arg1, arg2, ...)}
One or more lines showing the synopsis of the function(s) and variables docu-
mented in the file. These are set verbatim in typewriter font.
The usage information specified should in general match the function definition
exactly (such that automatic checking for consistency between code and docu-
mentation is possible). Otherwise, include a \synopsis section with the actual
definition.
For example, 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, ‘[Link]’ contains
Chapter 2: Writing R documentation files 18
\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)
...
}
Use \method{generic }{class } to indicate the name of an S3 method for
the generic function generic for objects inheriting from class "class ". In the
printed versions, this will come out as generic (reflecting the understanding that
methods should not be invoked directly but via method dispatch), but codoc()
and other QC tools always have access to the full name.
For example, ‘[Link]’ contains
\usage{
\method{print}{ts}(x, calendar, \dots)
}
Usage for replacement functions should be given in the style of dim(x) <- value
rather than explicitly indicating the name of the replacement function ("dim<-"
in the above). Similarly, one can use \method{generic }{class }(arglist )
<- value to indicate the usage of an S3 replacement method for the generic
replacement function "generic <-" for objects inheriting from class "class ".
\arguments{...}
Description of the function’s arguments, using an entry of the form
\item{arg_i }{Description of arg_i.}
for each element of the argument list. There may be optional text before and
after these entries.
\details{...}
A detailed if possible precise description of the functionality provided, extending
the basic information in the \description slot.
\value{...}
Description of the function’s return value.
If a list with multiple values is returned, you can use entries of the form
\item{comp_i }{Description of comp_i.}
for each component of the list returned. Optional text may precede this list
(see the introductory example for rle).
\references{...}
A section with references to the literature. Use \url{} for web pointers.
\note{...}
Use this for a special note you want to have pointed out.
For example, ‘[Link]’ contains
Chapter 2: Writing R documentation files 19
\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.
...
}
\author{...}
Information about the author(s) of the Rd file. Use \email{} without extra
delimiters (‘( )’ or ‘< >’) to specify email addresses, or \url{} for web pointers.
\seealso{...}
Pointers to related R objects, using \code{\link{...}} to refer to them (\code
is the correct markup for R object names, and \link produces hyperlinks in
output formats which support this. See Section 2.3 [Marking text], page 22,
and Section 2.5 [Cross-references], page 23).
\examples{...}
Examples of how to use the function. These are set as formatted in typewriter
font: see Section 2.7 [Insertions], page 24 for when characters need to be es-
caped.
Examples are not only useful for documentation purposes, but also provide test
code used for diagnostic checking of R. By default, text inside \examples{}
will be displayed in the output of the help page and run by R CMD check. You
can use \dontrun{} for commands that should only be shown, but not run,
and \dontshow{} for extra commands for testing that should not be shown to
users, but will be run by example(). (Previously this was called \testonly,
and that is still accepted.)
For example,
x <- runif(10) # Shown and run.
\dontrun{plot(x)} # Only shown.
\dontshow{log(x)} # Only run.
Thus, example code not included in \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). As from R 1.8.0,
code included in \dontrun is indicated by comments in the processed help files.
Data needed for making the examples executable can be obtained by random
number generation (for example, x <- rnorm(100)), or by using standard data
sets loadable via data() (see ?data for more info).
\keyword{key }
Each \keyword entry should specify one of the standard keywords (as listed
in the file ‘R_HOME /doc/[Link]’). There must be at least one \keyword
entry, but can be more that one if the R object being documented falls into
more than one category.
The special keyword ‘internal’ marks a page of internal objects that are
not part of the packages’ API. If the help page for object foo has keyword
‘internal’, then help(foo) gives this help page, but foo is excluded from
several object indices, like the alphabetical list of objects in the html help
system.
Chapter 2: Writing R documentation files 20
The structure of Rd files which document R data sets is slightly different. Whereas sections
such as \arguments and \value are not needed, the format and source of the data should
be explained.
As an example, let us look at ‘src/library/base/man/[Link]’ which documents
the standard R data set rivers.
\name{rivers}
\docType{data}
\alias{rivers}
\title{Lengths of Major North American Rivers}
\description{
This data set gives the lengths (in miles) of 141 \dQuote{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}
Structure of and special markup for documenting S4 classes and methods are still under
development. In any case, to allow for making full use of the potential of the on-line
documentation system, all user-visible S4 classes and methods in a package should at least
have a suitable \alias entry in one of the package’s Rd files. If a package has methods for
a function defined originally somewhere else, and does not change the underlying default
method for the function, the package is responsible for documenting the methods it creates,
but not for the function itself or the default method.
The topic names (\alias entries) for S4 classes and methods are of the form
class-class
generic,signature_list-method
where signature list contains the names of the classes in the signature of the method (with-
out quotes) separated by ‘,’, with ‘ANY’ used for arguments without an explicit specifica-
tion. E.g., ‘genericFunction-class’ is the topic name for documentation for the S4 class
"genericFunction", and ‘coerce,ANY,NULL-method’ is the topic name for documentation
for the S4 method for coerce for signature c("ANY", "NULL"). It is crucial not to use
different topic names, as otherwise the facilities for getting on-line documentation on S4
classes and methods via ‘?’ are bypassed.
Skeletons of documentation for S4 classes and methods can be generated by using the
functions promptClass() and promptMethods(), respectively, from package methods. If it
is necessary or desired to provide an explicit function synopsis (in a \usage section) for an
S4 method (e.g., if it has “surprising arguments” to be mentioned explicitly) , one can use
the special markup
\S4method{generic }{signature_list }(argument_list )
(e.g., ‘\S4method{coerce}{ANY,NULL}(from, to)’).
See help("Documentation", package = "methods") for more information on using and
creating on-line documentation for S4 classes and methods.
2.2 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 \cr.
In addition to the predefined sections (such as \description{}, \value{}, etc.), you
can “define” arbitrary ones by \section{section_title }{...}. For example
\section{Warning}{You must not call this function unless ...}
For consistency with the pre-assigned sections, the section name (the first argument to
\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 \note, \seealso and the examples), no matter where they appear in the
input.
Chapter 2: Writing R documentation files 22
The following logical markup commands are available for emphasizing or quoting text.
\emph{text }
\strong{text }
Emphasize text using italic and bold font if possible; \strong is stronger.
\bold{text }
Set text in bold font if possible.
\sQuote{text }
\dQuote{text }
Portably single or double quote text (without hard-wiring the quotation marks).
The following logical markup commands are available for indicating specific kinds of
text.
\code{text }
Indicate text that is a literal example of a piece of a program, e.g., a fragment
of R code or the name of an R object, using typewriter font if possible. Only
percent signs and unpaired braces always need to be escaped (by a backslash)
inside \code: backslash will need to be escaped if it precedes ‘%’, ‘{’ or ‘}’.
\preformatted{text }
Indicate text that is a literal example of a piece of a program, using typewriter
font if possible. The same characters need to be escaped as for \code. All other
formatting, e.g. line breaks, is preserved. The closing brace should be on a line
by itself.
\kbd{keyboard-characters }
Indicate keyboard input, using slanted typewriter font if possible, so users
can distinguish the characters they are supposed to type from those the com-
puter outputs.
\samp{text }
Indicate text that is a literal example of a sequence of characters.
\pkg{package-name }
Indicate the name of an R package.
\file{file-name }
Indicate the name of a file. Note that special characters do need to be escaped.
\email{email-address }
Indicate an electronic mail address.
\url{uniform-resource-locator }
Indicate a uniform resource locator (url) for the World Wide Web.
\var{metasyntactic-variable }
Indicate a metasyntactic variable.
\env{environment-variable }
Indicate an environment variable.
Chapter 2: Writing R documentation files 23
\option{option }
Indicate a command-line option.
\command{command-name }
Indicate the name of a command.
\dfn{term }
Indicate the introductory or defining use of a term.
\cite{reference }
Indicate a reference without a direct cross-reference via \link (see Section 2.5
[Cross-references], page 23), such as the name of a book.
\acronym{acronym }
Indicate an acronym (an abbreviation written in all capital letters), such as
gnu.
Note that unless explicitly stated otherwise, special characters (see Section 2.7 [Inser-
tions], page 24) must be escaped inside the above markup commands.
The \itemize and \enumerate commands take a single argument, within which there may
be one or more \item commands. The text following each \item is formatted as one or
more paragraphs, suitably indented and with the first paragraph marked with a bullet point
(\itemize) or a number (\enumerate).
\itemize and \enumerate commands may be nested.
The \describe command is similar to \itemize but allows initial labels to be specified.
The \items take two arguments, the label and the body of the item, in exactly the same
way as argument and value \items. \describe commands are mapped to <DL> lists in
html and \description lists in LaTEX.
The \tabular command takes two arguments. The first gives for each of the columns the
required alignment (‘l’ for left-justification, ‘r’ for right-justification or ‘c’ for centering.)
The second argument consists of an arbitrary number of lines separated by \cr, and with
fields separated by \tab. For example:
\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)
}
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).
2.5 Cross-references
section of the help page, see Section 2.1 [Rd format], page 16. (This only affects the
creation of hyperlinks, for example in the html pages used by [Link]() and the PDF
version of the reference manual.)
There are optional arguments specified as \link[pkg ]{foo } and \link[pkg:bar ]{foo }
to link to the package pkg with topic (file?) foo and bar respectively.
2.6 Mathematics
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
\eqn{latex }{ascii } and \deqn{latex }{ascii } are used. Where \eqn is used for “in-
line” formulae (corresponding to TEX’s $...$, \deqn gives “displayed equations” (as in
LaTEX’s displaymath environment, or TEX’s $$...$$).
Both commands can also be used as \eqn{latexascii } (only one argument) which then
is used for both latex and ascii.
The following example is from ‘[Link]’:
\deqn{p(x) = \frac{\lambda^x e^{-\lambda}}{x!}}{%
p(x) = lambda^x exp(-lambda)/x!}
for \eqn{x = 0, 1, 2, \ldots}.
For the LaTEX manual, this becomes
−λ
e
p(x) = λx
x!
for x = 0, 1, 2, . . ..
for x = 0, 1, 2, ....
2.7 Insertions
Use \R for the R system itself (you don’t need extra ‘{}’ or ‘\’). Use \dots for the dots in
function argument lists ‘...’, and \ldots for ellipsis dots in ordinary text.
After a ‘%’, 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 (‘\’) by escaping it by another backslash. (Note that \cr
is used for generating line breaks.)
The “comment” character ‘%’ and unpaired braces1 always need to be escaped by ‘\’, and
‘\\’ can be (but rarely needs to be) used for backslash. Inside the verbatim-like commands
1
See the examples section in the file ‘[Link]’ for an example.
Chapter 2: Writing R documentation files 25
(\code, \preformatted and \examples), no other characters are special. Note that \file
is not a verbatim-like command.
In “regular” text (no verbatim, no \eqn, . . . ), you currently must escape most LaTEX
special characters, i.e., besides ‘%’, ‘{’, and ‘}’, the four specials ‘$’, ‘#’, and ‘_’ are produced
by preceding each with a ‘\’. (‘&’ can also be escaped, but need not be.) Further, enter ‘^’
as \eqn{\mbox{\textasciicircum}}{^}, and ‘~’ by \eqn{\mbox{\textasciitilde}}{~}
or \eqn{\sim}{~} (for a short and long tilde respectively). Also, ‘<’, ‘>’, and ‘|’ must only
be used in math mode, i.e., within \eqn or \deqn.
2.8 Indices
The \alias command (see Section 2.1.1 [Documenting functions], page 17) is used for the
“topics” documented, including all R objects in a package such as functions and variables,
data sets, and S4 classes and methods (see Section 2.1.3 [Documenting S4 classes and
methods], page 21). The on-line help system searches the index data base consisting of all
aliases.
In addition, it is possible to provide “concept index entries” using \concept, which
can be used for [Link]() lookups. E.g., file ‘[Link]’ in the standard add-on
package ctest contains
\concept{Kendall correlation coefficient}
\concept{Pearson correlation coefficient}
\concept{Spearman correlation coefficient}
so that e.g. [Link]("Spearman") will succeed in finding the help page for the test
for association between paired samples using Spearman’s ρ.
(Note that [Link]() only uses “sections” of documentation objects with no addi-
tional markup.)
Sometimes the documentation needs to differ by platform. Currently two OS-specific options
are available, ‘unix’ and ‘windows’, and lines in the help source file can be enclosed in
#ifdef OS
...
#endif
or
#ifndef OS
...
#endif
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 ‘unix’ or ‘windows’
subdirectory.
Chapter 2: Writing R documentation files 26
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.
Using 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,
LaTEX, and S 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. 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. R CMD Rd2dvi generates DVI (or, if 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 ‘DESCRIPTION’ files.
Finally, R CMD Sd2Rd converts S version 3 documentation files (which use an extended
Nroff format) and S version 4 documentation (which uses SGML markup) to Rd format.
This is useful when porting a package originally written for the S system to R. S version 3
files usually have extension ‘.d’, whereas version 4 ones have extension ‘.sgml’ or ‘.sgm’.
The exact usage and a detailed list of available options for each of the above commands
can be obtained by running R CMD command --help, e.g., R CMD Rdconv --help. All avail-
able commands can be listed using R --help.
All of these have Windows equivalents. For most just replace ‘R CMD’ by ‘Rcmd’, with
the exception that it is Rcmd [Link] (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.)
Chapter 3: Tidying and profiling R code 27
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
‘<-’. 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.
1. The option [Link] can be set to FALSE before the code is loaded into R.
2. The stored source code can be removed by removing the source attribute, for example
by
attr(myfun, "source") <- NULL
In each case if we then list the function we will get the standard layout.
Suppose we have a file of functions ‘myfuns.R’ that we want to tidy up. Create a file
‘tidy.R’ containing
options([Link] = FALSE)
source("myfuns.R")
dump(ls(all = TRUE), file = "[Link].R")
and run R with this as the source file, for example by R --vanilla < tidy.R (Unix) or
Rterm --vanilla < tidy.R (Windows) or by pasting into an R session. Then the file
‘[Link].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 ess Emacs package. See Appendix B [R coding standards], page 74 for style
options within the ESS[S] mode recommended for the source code of R itself.
The 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 ‘[Link]’ in
the working directory). Then the function summaryRprof or the command-line utility R CMD
Rprof [Link] can be used to summarize the activity.
As an example, consider the following code (from Venables & Ripley, 1999).
% self % total
self seconds total seconds name
5.42 4.38 10.13 8.18 "paste"
3.37 2.72 6.71 5.42 "[Link]"
3.29 2.66 5.00 4.04 "[Link]"
3.20 2.58 4.29 3.46 "[Link]"
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 "[Link]<-"
...
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.
R CMD Rprof (or Rcmd Rprof under Windows) uses a Perl script that may be much faster
than summaryRprof for large files (about 4 times faster for the example above). On the
other hand 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.
Chapter 4: System and foreign language interfaces 30
Access to operating system functions is via the R function 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 command that will be passed for execution (not necessarily by a
shell) and the second argument will be internal which if true will collect the output of the
command into an R character vector.
The function [Link] is available for timing (although the information available
may be limited on non-Unix-like platforms).
These two functions provide a standard interface to compiled code that has been linked
into R, either at build time or via [Link] (see Section 4.3 [[Link] and [Link]],
page 31). They are primarily intended for compiled C and FORTRAN code respectively,
but the .C function can be used with other languages which can generate C interfaces, for
example C++ (see Section 4.6 [Interfacing C++ code], page 35).
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 symbol.C and [Link]; that
the symbol is loaded can be tested by, for example, [Link](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.
C type Rcomplex is a structure with double members r and i defined in the header
file ‘Complex.h’ included by ‘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
.C, but it is better to use one of the other interfaces. An exception is passing an R function
for use with call_R, when the object can be handled as void * en route to call_R, but
even there .Call is to be preferred. Similarly, passing an R list as an argument to a C
Chapter 4: System and foreign language interfaces 31
routine should be done using the .Call interface. If one does use the .C function to pass a
list as an argument, it is visible to the routine as an array in C of SEXP types (i.e., 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 double to C as float * or FOR-
TRAN as REAL by setting the attribute Csingle, most conveniently by using the R functions
[Link], single or [Link]. This is intended only to be used to aid interfacing
to existing C or FORTRAN code.
Unless formal argument NAOK is true, all the other arguments are checked for missing
values NA and for the ieee special values NaN, Inf and -Inf, and the presence of any of
these generates an error. If it is true, these values are passed unchecked.
Argument 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 float * or REAL if
DUP=FALSE.
Finally, argument PACKAGE confines the search for the symbol name to a specific shared
object (or use "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 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
.C by
void convolve(double *a, int *na, double *b, int *nb, double *ab)
{
int i, j, nab = *na + *nb - 1;
Compiled code to be used with R is loaded as a shared object (Unix, see Section 4.5 [Creating
shared objects], page 35 for more information) or DLL (Windows).
The first argument to both functions is a character string giving the path to the object.
Programmers should not assume a specific file extension for the object/DLL (such as ‘.so’)
but use a construction like
for platform independence. On Unix systems the path supplied to [Link] can be an
absolute path, one relative to the current directory or, if it starts with ‘~’, relative to the
user’s home directory.
Loading is most often done via a call to [Link] in the .[Link] function of
a package. This has the form
Under some Unix systems there is a choice of how the symbols are resolved when the
object is loaded, governed by the arguments local and now. Only use these if really neces-
sary: in particular using now=FALSE and then calling an unresolved symbol will terminate
R unceremoniously.
R looks for the symbol named R_init_mylib. Similarly, when unloading the object, R looks
for a routine named R_unload_lib , e.g., 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 DllInfo which is defined in the ‘Rdynload.h’ file in the ‘R_ext’ directory.
The following example shows templates for the initialization and unload routines for the
mylib DLL.
Chapter 4: System and foreign language interfaces 33
#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. */
}
If a shared object/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 PACKAGE argument provides a good way to avoid any ambiguity in
which occurrence is meant.
.C R_CMethodDef
.Call R_CallMethodDef
.Fortran R_FortranMethodDef
.External R_ExternalMethodDef
numeric REALSXP
integer INTSXP
logical LGLSXP
single SINGLESXP
character STRSXP
list VECSXP
When R unloads a shared object/DLL, any registered routines are automatically re-
moved. 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., mva, ctest, lqs). Also, there is a brief, high-level introduction in 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 GccTranslationUnit
module on the Omegahat Web site at [Link]
for more information.
Under Unix, shared objects for loading into R can be created using R CMD SHLIB. This
accepts as arguments a list of files which must be object files (with extension ‘.o’) or
C, C++, or FORTRAN sources (with extensions ‘.c’, ‘.cc’ or ‘.cpp’ or ‘.C’, and ‘.f’,
respectively). See R CMD SHLIB --help, or the on-line help for 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 PKG_CPPFLAGS (for the C preprocessor, typically ‘-I’ flags),
PKG_CFLAGS, PKG_CXXFLAGS, and PKG_FFLAGS (for the C, C++, and FORTRAN compilers,
respectively) in the file ‘Makevars’ in the compilation directory, or write a ‘Makefile’ in
the compilation directory containing the rules required (or, of course, create the object files
directly from the command line). Similarly, variable PKG_LIBS in ‘Makevars’ can be used
for additional ‘-l’ and ‘-L’ flags to be passed to the linker when building the shared object.
If an add-on package pkg contains C, C++, or FORTRAN code in its ‘src’ subdirectory,
R CMD INSTALL creates a shared object (for loading into R in the .[Link] function of
the package) either automatically using the above R CMD SHLIB mechanism, or using Make
if directory ‘src’ contains a ‘Makefile’. In both cases, if file ‘Makevars’ exists it is read
first when invoking make. If a ‘Makefile’ is really needed or provided, it needs to ensure
that the shared object created is linked against all FORTRAN 77 intrinsic and run-time
libraries that R was linked against; Make variable FLIBS contains this information.
Suppose we have the following hypothetical C++ library, consisting of the two files ‘[Link]’
and ‘[Link]’, and implementing the two classes X and Y which we want to use in R.
Chapter 4: System and foreign language interfaces 36
// [Link]
class X {
public: X (); ~X ();
};
class Y {
public: Y (); ~Y ();
};
// [Link]
#include <iostream>
#include "[Link]"
static Y y;
To use with R, the only thing we have to do is writing a wrapper function and ensuring
that the function is enclosed in
extern "C" {
}
For example,
// X_main.cc:
#include "[Link]"
extern "C" {
void X_main () {
X x;
}
} // extern "C"
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 Y) are not called. On a properly configured Unix system
(support for C++ was added in R version 1.1), one can simply use
R CMD SHLIB [Link] X_main.cc
to create the shared object, typically ‘[Link]’ (the file name extension may be different on
your platform). Now starting R yields
R : Copyright 2000, The R Development Core Team
Version 1.1.0 Under development (unstable) (April 14, 2000)
...
Type "q()" to quit R.
Chapter 4: System and foreign language interfaces 37
Using C code to speed up the execution of an R function is often very fruitful. Traditionally
this has been done via the .C function in R. 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 call_R
(also known as 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 .Call and .External function. The syntax for the calling function in R in
each case is similar to that of .C, but the two functions have rather different C interfaces.
Generally the .Call interface (which is modelled on the interface of the same name in S
version 4) is a little simpler to use, but .External is a little more general.
A call to .Call is very similar to .C, for example
.Call("convolve2", a, b)
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
#include <R.h>
#include <Rinternals.h>
Here args is a 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 ‘Rinternals.h’ or some higher-level macros defined in
‘Rdefines.h’. See Section 4.8 [Interface functions .Call and .External], page 44 for details
on .Call and .External.
Before you decide to use .Call or .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 .C is enough. If the task to be performed in C is
simple enough requiring no call to R, .C suffices. The new interfaces are recent additions
to S and R, and a great deal of useful code has been written using just .C before they
were available. The .Call and .External interfaces allow much more control, but they
also impose much greater responsibilities so need to be used with care. Neither .Call nor
.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 .Internal calls. A public subset of these is defined in the
header file ‘Rinternals.h’ in the directory ‘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
S version 4 interface .Call, which are defined in the header file ‘Rdefines.h’. This is a
somewhat simpler approach, and is certainly to be preferred if the code might be shared
with S 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 SEXP 1 , which is a pointer to a
structure with typedef SEXPREC. Think of this structure as a 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.
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 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.)
1
SEXP is an acronym for S imple EXP ression, common in LISP-like language syntaxes.
Chapter 4: System and foreign language interfaces 39
SEXP ab;
....
PROTECT(ab = NEW_NUMERIC(2));
NUMERIC_POINTER(ab)[0] = 123.45;
NUMERIC_POINTER(ab)[1] = 67.89;
UNPROTECT(1);
and then those in ‘Rinternals.h’:
#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);
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 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 PROTECT everything in sight and UNPROTECT several thousand objects
at the end. It will almost invariably be possible to either assign the objects as part of
Chapter 4: System and foreign language interfaces 40
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 UNPROTECT_PTR(s ) that unprotects the object pointed to by
the SEXP 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 ‘src/main/plot3d.c’).
Sometimes an object is changed (for example coerced or grown) yet the current value
needs to be protected. For these cases PROTECT_WITH_INDEX saves an index of the protection
location that can be used to replace the protected value using REPROTECT. For example (from
the internal code for optim)
PROTECT_INDEX ipx;
....
PROTECT_WITH_INDEX(s = eval(OS->R_fcall, OS->R_env), &ipx);
REPROTECT(s = coerceVector(s, REALSXP), ipx);
For many purposes it is sufficient to allocate R objects and manipulate those. There are
quite a few allocXxx functions defined in ‘Rinternals.h’—you may want to explore them.
These allocate R objects of various types, and for the standard vector types there are NEW_
XXX macros defined in ‘Rdefines.h’.
If storage is required for C objects during the calculations this is best allocating by calling
R_alloc; see Section 5.1 [Memory allocation], page 57. 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.
Users of the ‘Rinternals.h’ macros will need to know how the R types are known internally:
this is more or less completely hidden if the ‘Rdefines.h’ macros are used.
The different R data types are represented in C by SEXPTYPE. Some of these are
familiar from R and some are internal data types. The usual R object modes are given in
the table.
SEXPTYPE R equivalent
SYMSXP name/symbol
CLOSXP function or function closure
ENVSXP environment
Among the important internal SEXPTYPEs are LANGSXP, CHARSXP etc. (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 isReal, isInteger
and isString to do type checking. See the header file ‘Rinternals.h’ for definitions of
other such functions. All of these take a SEXP as argument and return 1 or 0 to indicate
TRUE or FALSE. Once again there are two ways to do this, and ‘Rdefines.h’ has macros
such as IS_NUMERIC.
What happens if the SEXP is not of the correct type? Sometimes you have no other option
except to generate an error. You can use the function error for this. It is usually better to
coerce the object to the correct type. For example, if you find that an SEXP is of the type
INTEGER, but you need a REAL object, you can change the type by using, equivalently,
PROTECT(newSexp = coerceVector(oldSexp, REALSXP));
or
PROTECT(newSexp = AS_NUMERIC(oldSexp ));
Protection is needed as a new object is created; the object formerly pointed to by the SEXP
is still protected but now unused.
All the coercion functions do their own error-checking, and generate NAs 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.
4.7.4 Attributes
Many R objects have attributes: some of the most useful are classes and the dim and
dimnames that mark objects as matrices or arrays. It can also be helpful to work with the
names attribute of vectors.
To illustrate this, let us write code to take the outer product of two vectors (which outer
and %o% already do). As usual the R code is simple
out <- function(x, y)
{
[Link](x) <- [Link](y) <- "double"
.Call("out", x, y)
}
where we expect x and y to be numeric vectors (possibly integer), possibly with names.
This time we do the coercion in the calling R code.
C code to do the computations is
Chapter 4: System and foreign language interfaces 42
#include <R.h>
#include <Rinternals.h>
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);
}
but we would like to set the dimnames of the result. Although allocMatrix provides a
short cut, we will show how to set the dim attribute directly.
#include <R.h>
#include <Rinternals.h>
What happens if we want to add an attribute that is not pre-defined? We need to add a
symbol for it via a call to install. Suppose for illustration we wanted to add an attribute
"version" with value 3.0. We could use
SEXP version;
PROTECT(version = allocVector(REALSXP, 1));
REAL(version)[0] = 3.0;
setAttrib(ans, install("version"), version);
UNPROTECT(1);
Using 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.
4.7.5 Classes
In R the class is just the attribute named "class" so it can be handled as such, but there
is a shortcut classgets. Suppose we want to give the return value in our example the class
"mat". We can use
#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);
}
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 mkChar.
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
list is isNewList, and we need allocVector(VECSXP, n ) and not allocList(n ).
List elements can be retrieved or set by direct access to the elements of the generic
vector. Suppose we have a list object
a <- list(f=1, g=2, h=3)
Then we can access a$g as a[[2]] by
double g;
....
g = REAL(VECTOR_ELT(a, 1))[0];
This can rapidly become tedious, and the following function (based on one in package
nls) is very useful:
/* get the list element named str, or return NULL */
It will be usual that all the R objects needed in our C computations are passed as arguments
to .Call or .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 get(name, envir = rho).
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);
}
The main work is done by findVar, but to use it we need to install name as a name in
the symbol table. As we wanted the value for internal use, we return NULL.
Similar functions with syntax
void defineVar(SEXP symbol, SEXP value, SEXP rho)
void setVar(SEXP symbol, SEXP value, SEXP rho)
can be used to assign values to R variables. defineVar creates a new binding or changes
the value of an existing binding in the specified environment frame; it is the analogue of
assign(symbol, value, envir = rho, inherits = FALSE), but unlike assign, defineVar
does not make a copy of the object value.2 setVar searches for an existing binding for
symbol in rho or its enclosing environments. If a binding is found, its value is changed to
value. Otherwise, a new binding with the specified value is created in the global environ-
ment. This corresponds to assign(symbol, value, envir = rho, inherits = TRUE).
Let us convert our finite convolution example to use .Call, first using the ‘Rdefines.h’
macros. The calling function in R is
conv <- function(a, b) .Call("convolve2", a, b)
which could hardly be simpler, but as we shall see all the type checking must be transferred
to the C code, which is
#include <R.h>
#include <Rdefines.h>
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);
}
Note that unlike the macros in S 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.
#include <R.h>
#include <Rinternals.h>
We can use the same example to illustrate .External. The R code changes only by replacing
.Call by .External
conv <- function(a, b) .External("convolveE", a, b)
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.
#include <R.h>
#include <Rinternals.h>
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
first = CADR(args);
second = CADDR(args);
third = CADDDR(args);
fourth = CAD4R(args);
provide convenient ways to access the first four arguments. More generally we can use the
CDR and CAR macros as in
args = CDR(args); a = CAR(args);
args = CDR(args); b = CAR(args);
which clearly allows us to extract an unlimited number of arguments (whereas .Call has a
limit, albeit at 65 not a small one).
More usefully, the .External interface provides an easy way to handle calls with a
variable number of arguments, as 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 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.
#include <R_ext/PrtUtil.h>
One piece of error-checking the .C call does (unless NAOK is true) is to check for missing
(NA) and ieee special values (Inf, -Inf and NaN) and give an error if any are found. With
the .Call interface these will be passed to our code. In this example the special values are
no problem, as ieee arithmetic will handle them correctly. In the current implementation
this is also true of NA as it is a type of NaN, but it is unwise to rely on such details. Thus we
will re-write the code to handle NAs using macros defined in ‘Arith.h’ included by ‘R.h’.
The code changes are the same in any of the versions of convolve2 or convolveE:
...
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];
...
Note that the ISNA macro, and the similar macros ISNAN (which checks for NaN or NA)
and R_FINITE (which is false for NA and all the special values), only apply to numeric values
Chapter 4: System and foreign language interfaces 48
of type double. Missingness of integers, logicals and character strings can be tested by
equality to the constants NA_INTEGER, NA_LOGICAL and NA_STRING. These and NA_REAL
can be used to set elements of R vectors to NA.
The constants R_NaN, R_PosInf, R_NegInf and R_NaReal can be used to set doubles to
the special values.
We noted that the 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
the equivalent of the interpreted R code eval(expr, envir = rho), although we can also
make use of findVar, defineVar and findFun (which restricts the search to functions).
To see how this might be applied, here is a simplified internal version of lapply for
expressions, used as
with C code
It would be closer to lapply if we could pass in a function rather than an expression. One
way to do this is 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 ‘src/main/optimize.c’.
Chapter 4: System and foreign language interfaces 49
4.9.1 Zero-finding
In this section we re-work the example of call_S in Becker, Chambers & Wilks (1988) on
finding a zero of a univariate function, which used to be used as an example for call_R in
the now defunct demo(dynload). The R code and an example are
Chapter 4: System and foreign language interfaces 50
where this time we do the coercion and error-checking in the R code. The C code is
SEXP mkans(double x)
{
SEXP ans;
PROTECT(ans = allocVector(REALSXP, 1));
REAL(ans)[0] = x;
UNPROTECT(1);
return ans;
}
double feval(double x, SEXP f, SEXP rho)
{
defineVar(install("x"), mkans(x), rho);
return(REAL(eval(f, rho))[0]);
}
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;
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");
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;
}
}
}
The C code is essentially unchanged from the call_R version, just using a couple of functions
to convert from double to SEXP and to evaluate [Link].
Chapter 4: System and foreign language interfaces 51
We will use a longer example (by Saikat DebRoy) to illustrate the use of evaluation and
.External. This calculates numerical derivatives, something that could be done as effec-
tively in interpreted R code but may be needed as part of a larger C calculation.
An interpreted R version and an example are
[Link] <- function(expr, theta, rho=[Link]([Link]()))
{
eps <- sqrt(.Machine$[Link])
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
[Link](sin(omega*x*y), c("x", "y"))
where expr is an expression, theta a character vector of variable names and rho the envi-
ronment to be used.
For the compiled version the call from R will be
.External("numeric_deriv", expr, theta, rho )
are directly dealing with original R memory locations here, R does the evaluation for the
changed parameter value.
for(j = 0; j < LENGTH(ans); j++)
REAL(gradient)[j + start] =
(REAL(ans1)[j] - REAL(ans)[j])/delta;
REAL(par)[0] = tt;
UNPROTECT(2);
}
Now, we compute the i’th column of the gradient matrix. Note how it is accessed: R stores
matrices by column (like FORTRAN).
PROTECT(dimnames = allocVector(VECSXP, 2));
SET_VECTOR_ELT(dimnames, 1, theta);
dimnamesgets(gradient, dimnames);
setAttrib(ans, install("gradient"), gradient);
UNPROTECT(3);
return ans;
}
First we add column names to the gradient matrix. This is done by allocating a list (a
VECSXP) whose first element, the row names, is NULL (the default) and the second element,
the column names, is set as theta. This list is then assigned as the attribute having the
symbol R_DimNamesSymbol. Finally we set the gradient matrix as the gradient attribute of
ans, unprotect the remaining protected locations and return the answer ans.
Suppose an R extension want to accept an R expression from the user and evaluate it.
The previous section covered evaluation, but the expression will be entered as text and
needs to be parsed first. A small part of R’s parse interface is declared in header file
‘R_ext/Parse.h’3 .
An example of the usage can be found in the (example) Windows package windlgs
included in the R source tres. The essential part is
3
This was added at R version 1.8.0, and is only guaranteed to show the current interface: it is liable to
change.
Chapter 4: System and foreign language interfaces 54
#include <Rinternals.h>
#include <R_ext/Parse.h>
SEXP menu_ttest3()
{
char cmd[256];
SEXP cmdSexp, cmdexpr, ans = R_NilValue;
int i;
ParseStatus status;
...
if(done == 1) {
PROTECT(cmdSexp = allocVector(STRSXP, 1));
SET_STRING_ELT(cmdSexp, 0, mkChar(cmd));
cmdexpr = PROTECT(R_ParseVector(cmdSexp, -1, &status));
if (status != PARSE_OK) {
UNPROTECT(2);
error("invalid call %s", cmd);
}
/* Loop is needed here as EXPSEXP will be of length > 1 */
for(i = 0; i < length(cmdexpr); i++)
ans = eval(VECTOR_ELT(cmdexpr, i), R_GlobalEnv);
UNPROTECT(2);
}
return ans;
}
Note that a single line of text may give rise to more than one R expression.
Sooner or later programmers will be faced with the need to debug compiled code loaded
into R. Some “tricks” are worth knowing.
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
• Call the debugger on the R executable, for example by R -d gdb.
• Start R.
• At the R prompt, use [Link] or library to load your shared object.
• Send an interrupt signal. This will put you back to the debugger prompt.
• Set the breakpoints in your code.
• Continue execution of R by typing signal 0hRETi.
gdb .../bin/[Link]
(gdb) break WinMain
(gdb) run
[ stops with [Link] loaded ]
(gdb) break R_ReadConsole
(gdb) continue
[ stops with console running ]
(gdb) continue
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.
The key to inspecting R objects from compiled code is the function PrintValue(SEXP s )
which uses the normal R printing mechanisms to print the R object pointed to by s, or the
safer version R_PV(SEXP s ) which will only print ‘objects’.
One way to make use to PrintValue is to insert suitable calls into the code to be
debugged.
Another way is to call R_PV from the symbolic debugger. (PrintValue is hidden as
Rf_PrintValue.) For example, from gdb we can use
(gdb) p R_PV(ab)
using the object 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
By setting a breakpoint at do_get and typing get("DF") at the R prompt, one can find
out the address in memory of DF, for example
Chapter 4: System and foreign language interfaces 56
$[Link]
[1] "1" "2" "3"
$class
[1] "[Link]"
$3 = void
To find out where exactly the corresponding information is stored, one needs to go
“deeper”:
(gdb) set $a = $1->attrib
(gdb) p $a->[Link]->[Link]->[Link].c
$4 = 0x405d40e8 "names"
(gdb) p $a->[Link]->[Link].s[1]->[Link].c
$5 = 0x40634378 "b"
(gdb) p $1->[Link].s[0]->[Link].i[0]
$6 = 1
(gdb) p $1->[Link].s[1]->[Link].i[1]
$7 = 5
Chapter 5: The R api: entry points for C code 57
Here R will reclaim the memory at the end of the call to .C. Use
char* R_alloc(long n, int size )
which allocates n units of size bytes each. A typical usage (from package mva) is
x = (int *) R_alloc(nrows(merge)+2, sizeof(int));
There is a similar call, S_alloc, for compatibility with S, which differs only in zeroing
the memory allocated, and
S_realloc(char *p, long new, long old, int size )
which changes the allocation size from old to new units, and zeroes the additional units.
This memory is taken from the heap, and released at the end of the .C, .Call or
.External call. Users can also manage it, by noting the current position with a call to
vmaxget and clearing memory allocated subsequently by a call to vmaxset. This is only
recommended for experts.
1
notably with Windows headers
2
known problems are redefining error, length, vector and warning
Chapter 5: The R api: entry points for C code 58
The other form of memory allocation is an interface to 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
type * Calloc(size_t n, type )
type * Realloc(any *p, size_t n, type )
void Free(any *p )
providing analogues of calloc, realloc and free. If there is an error it is handled by R,
so if these routines return the memory has been successfully allocated or freed. Free will
set the pointer p to NULL. (Some but not all versions of S do so.)
The basic error handling routines are the equivalents of stop and warning in R code, and
use the same interface.
void error(const char * format, ...);
void warning(const char * format, ...);
These have the same call sequences as calls to 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 ‘%’ or might otherwise be interpreted as a format.)
If STRICT_R_HEADERS is not defined there is also an S-compatibility interface which uses
calls of the form
PROBLEM ...... ERROR
MESSAGE ...... WARN
PROBLEM ...... RECOVER(NULL_ENTRY)
MESSAGE ...... WARNING(NULL_ENTRY)
the last two being the forms available in all S versions. Here ‘......’ is a set of arguments to
printf, so can be a string or a format string followed by arguments separated by commas.
There are two interface function provided to call error and warning from FORTRAN code,
in each case with a simple character string argument. They are defined as
subroutine rexit(message )
subroutine rwarn(message )
Messages of more than 255 characters are truncated, with a warning.
GetRNGstate();
and after all the required variates have been generated, call
PutRNGstate();
These essentially read in (or create) .[Link] and write it out after use.
File ‘S.h’ defines seed_in and seed_out for S-compatibility rather than GetRNGstate
and PutRNGstate. These take a 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 rxxx functions can be accessed by including the header file
‘Rmath.h’; See Section 5.7.1 [Distribution functions], page 61. Those calls generate a single
variate and should also be enclosed in calls to GetRNGstate and PutRNGstate.
It is possible to compile R on a platform without iec 559 (more commonly known as ieee
754)-compatible arithmetic, so users should not assume that it is available. Rather a set
of functions is provided to test for NA, Inf, -Inf (which exists on all platforms) and NaN.
These functions are accessed via macros:
ISNA(x ) True for R’s NA only
ISNAN(x ) True for R’s NA and ieee NaN
R_FINITE(x ) False for Inf, -Inf, NA, NaN
and function R_IsNaN is true for NaN but not NA. Do use these rather than isnan or finite;
the latter in particular is often mendacious.
You can check for Inf or -Inf by testing equality to R_PosInf or R_NegInf, and set
(but not test) an NA as NA_REAL.
All of the above apply to double variables only. For integer variables there is a variable
accessed by the macro 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.
5.5 Printing
The most useful function for printing from a C routine compiled into R is Rprintf. This is
used in exactly the same way as printf, but is guaranteed to write to R’s output (which
might be a gui console rather than a file). It is wise to write complete lines (including the
"\n") before returning to R.
The function REprintf is similar but writes on the error stream (stderr) which may or
may not be different from the standard output stream. Functions Rvprintf and REvprintf
are the analogues using the vprintf interface.
Chapter 5: The R api: entry points for C code 60
In theory FORTRAN write and print statements can be used, but the output may not
interleave well with that of C, and will be invisible on gui interfaces. They are best avoided.
Three subroutines are provided to ease the output of information from FORTRAN code.
subroutine dblepr(label, nchar, data, ndata )
subroutine realpr(label, nchar, data, ndata )
subroutine intpr (label, nchar, data, ndata )
Here label is a character label of up to 255 characters, nchar is its length (which can be -1 if
the whole label is to be used), and data is an array of length at least ndata of the appropriate
type (double precision, real and integer respectively). These routines print the label
on one line and then print data as if it were an R vector on subsequent line(s). They work
with zero ndata, and so can be used to print a label alone.
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.
F77_SUB(name )
to define a function in C to be called from FORTRAN
F77_NAME(name )
to declare a FORTRAN routine in C before use
F77_CALL(name )
to call a FORTRAN routine from C
F77_COMDECL(name )
to declare a FORTRAN common block in C
F77_COM(name )
to access a FORTRAN common block from C
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
#include <R.h>
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 modreg, are a rich source of further examples.
R contains a large number of mathematical functions for its own use, for example numerical
linear algebra computations and special functions.
The header file ‘R_ext/Linpack.h’ contains details of the BLAS, LINPACK and EIS-
PACK 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 api, this set of subroutines is unlikely to change (but might be supplemented).
The header 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.
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:
double dnorm(double x, double mu, double sigma, int give_log );
double pnorm(double x, double mu, double sigma, int lower_tail,
int give_log );
double qnorm(double p, double mu, double sigma, int lower_tail,
int log_p );
double rnorm(double mu, double sigma );
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 lower tail
should be TRUE (or 1) for normal use, but can be FALSE (or 0) if the probability of the upper
tail is desired or specified.
Finally, give log should be non-zero if the result is required on log scale, and log p should
be non-zero if p has been specified on log scale.
Note that you directly get the cumulative (or “integrated”) hazard function, H(t) =
− log(1 − F (t)), by using
- pdist (t, ..., /*lower_tail = */ FALSE, /* give_log = */ TRUE)
or shorter (and more cryptic) - pdist (t, ..., 0, 1).
The random-variate generation routine rnorm returns one normal variate. See Section 5.3
[Random numbers], page 58, for the protocol in using the random-variate routines.
Note that these argument sequences are (apart from the names and that rnorm has no n)
exactly the same as the corresponding R functions of the same name, so the documentation
of the R functions can be used.
Chapter 5: The R api: entry points for C code 62
For reference, the following table gives the basic name (to be prefixed by ‘d’, ‘p’, ‘q’ or
‘r’ apart from the exceptions noted) and distribution-specific arguments for the complete
set of distributions.
beta beta a, b
non-central beta nbeta a, b, lambda
binomial binom n, p
Cauchy cauchy location, scale
chi-squared chisq df
non-central chi-squared nchisq df, lambda
exponential exp scale
F f n1, n2
non-central F nf (*) n1, n2, ncp
gamma gamma shape, scale
geometric geom p
hypergeometric hyper NR, NB, n
logistic logis location, scale
lognormal lnorm logmean, logsd
negative binomial nbinom n, p
normal norm mu, sigma
Poisson pois lambda
Student’s t t n
non-central t nt (*) df, delta
Studentized range tukey (*) rr, cc, df
uniform unif a, b
Weibull weibull shape, scale
Wilcoxon rank sum wilcox m, n
Wilcoxon signed rank signrank n
Entries marked only have ‘p’ and ‘q’ functions available. After a call to dwilcox, pwilcox
or qwilcox the function 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.
5.7.3 Utilities
There are a few other numerical utility functions available as entry points.
double R pow (double x, double y ) [Function]
double R pow di (double x, int i ) [Function]
R_pow(x, y ) and R_pow_di(x, i ) compute x ^y and x ^i , respectively using R_
FINITE checks and returning the proper result (the same as R) for the cases where x,
y or i are 0 or missing or infinite or NaN.
double pythag (double a, double b ) [Function]
pythag(a, b ) computes sqrt(a ^2 + b ^2) without overflow or destructive underflow:
for example it still works when both a and b are between 1e200 and 1e300 (in ieee
double precision).
double log1p (x ) [Function]
Computes log(1 + x ) (log 1 plus x ), accurately even for small x, i.e., |x| 1.
This may be provided by your platform, in which case it is not included in ‘Rmath.h’,
but is (probably) in ‘math.h’. For backwards compatibility with R versions prior to
1.5.0, the entry point Rf_log1p is still provided.
double expm1 (x ) [Function]
Computes exp(x ) - 1 (exp x minus 1 ), accurately even for small x, i.e., |x| 1.
This may be provided by your platform, in which case it is not included in ‘Rmath.h’,
but is (probably) in ‘math.h’.
int imax2 (int x, int y ) [Function]
int imin2 (int x, int y ) [Function]
double fmax2 (double x, double y ) [Function]
double fmin2 (double x, double y ) [Function]
Return the larger (max) or smaller (min) of two integer or double numbers, respec-
tively.
double sign (double x ) [Function]
Compute the signum function, where sign(x) is 1, 0, or −1, when x is positive, 0, or
negative, respectively.
Chapter 5: The R api: entry points for C code 64
R has a set of commonly used mathematical constants encompassing constants usually found
‘math.h’ and contains further ones that are used in statistical computations. All these are
defined to (at least) 30 digits accuracy in ‘Rmath.h’. The following definitions use ln(x)
for the natural logarithm (log(x) in R).
There are a set of constants (PI, DOUBLE_EPS) (and so on) defined3 in the included header
‘R_ext/Constants.h’, mainly for compatibility with S.
Further, the included header ‘R_ext/Boolean.h’ has constants TRUE and FALSE = 0 of
type Rboolean in order to provide a way of using “logical” variables in C consistently.
5.8 Optimization
The C code underlying optim can be accessed directly. The user needs to supply a function
to compute the function to be minimized, of the type
typedef double optimfn(int n, double *par, void *ex);
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
typedef void optimgr(int n, double *par, double *gr, void *ex);
which passes back the gradient in the gr argument. No function is provided for finite-
differencing, nor for approximating the Hessian at the result.
The interfaces are
• Nelder Mead:
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);
• BFGS:
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);
• Conjugate gradients:
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);
• Limited-memory BFGS with bounds:
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);
• Simulated annealing:
void samin(int n, double *x, double *Fmin, optimfn fn, int maxit,
int tmax, double temp, int trace, void *ex);
Many of the arguments are common to the various methods. n is the number of parameters,
x or xin is the starting parameters on entry and x the final parameters on exit, with final
value returned in Fmin. Most of the other parameters can be found from the help page
for optim: see the source code ‘src/appl/lbfgsb.c’ for the values of nbd, which specifies
which bounds are to be used.
3
unless STRICT_R_HEADERS is defined
Chapter 5: The R api: entry points for C code 66
5.9 Integration
The C code underlying integrate can be accessed directly. The user needs to supply a
vectorizing C function to compute the function to be integrated, of the type
typedef void integr_fn(double *x, int n, void *ex);
where x[] is both input and output and has length n, i.e., a C function, say fn, of type
integr_fn must basically do for(i in 1:n) x[i] := f(x[i], ex). The vectorization re-
quirement can be used to speed up the integrand instead of calling it n times. Note that
in the current implementation built on QUADPACK, n will be either 15 or 21. The ex ar-
gument 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.
• Finite:
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);
• Indefinite:
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);
Only the 3rd and 4th argument differ for the two integrators; for the definite integral, using
Rdqags, a and b are the integration interval bounds, whereas for an indefinite integral, using
Rdqagi, bound is the finite bound of the integration (if the integral is not doubly-infinite)
and inf is a code indicating the kind of integration range,
inf = 1 corresponds to (bound, +Inf),
inf = -1 corresponds to (-Inf, bound),
inf = 2 corresponds to (-Inf, +Inf),
f and ex define the integrand function, see above; epsabs and epsrel specify the ab-
solute and relative accuracy requested, result, abserr and last are the output com-
ponents value, [Link] and subdivisions of the R function integrate, where neval
gives the number of integrand function evaluations, and the error code ier is translated
to R’s integrate() $ message, look at that function definition. limit corresponds to
integrate(..., subdivisions = *). It seems you should always define the two work ar-
rays and the length of the second one as
lenw = 4 * limit;
iwork = (int *) R_alloc(limit, sizeof(int));
work = (double *) R_alloc(lenw, sizeof(double));
The comments in the source code in ‘src/appl/integrate.c’ give more details, partic-
ularly about reasons for failure (ier >= 1).
Chapter 5: The R api: entry points for C code 67
R has a fairly comprehensive set of sort routines which are made available to users’ C code.
These include the following.
void R max col (double* matrix, int* nr, int* nc, int* maxes ) [Function]
Given the nr by ny matrix matrix in row (“FORTRAN”) order, R_max_col() returns
in maxes [i -1] the column number of the maximal element in the i-th row (the same
as R’s [Link]() function).
Chapter 5: The R api: entry points for C code 68
There is also the internal function used to expand file names in several R functions, and
called directly by [Link].
The header files define USING_R, which should be used to test if the code is indeed being
used with R.
Header file ‘Rconfig.h’ (included by ‘R.h’) is used to define platform-specific macros
that are mainly for use in other header files. The macro WORDS_BIGENDIAN is defined on
big-endian systems (e.g. sparc-sun-solaris2.6) and not on little-endian systems (such as
i686 under Linux or Windows). It can be useful when manipulating binary files.
Header file ‘Rversion.h’ (not included by ‘R.h’ as from R 1.6.0) defines a macro R_
VERSION giving the version number encoded as an integer, plus a macro 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
#if defined(R_VERSION) && R_VERSION >= R_Version(0, 99, 0)
...
#endif
More detailed information is available in the macros R_MAJOR, R_MINOR, R_YEAR, R_MONTH
and R_DAY: see the header file ‘Rversion.h’ for their format. Note that the minor version
includes the patchlevel (as in ‘99.0’).
Chapter 5: The R api: entry points for C code 69
To add a further twist, which default is used when a user calls scale(x) in our example?
What if
[Link] <- function(x, center, scale = TRUE) NextMethod("scale")
and x has class 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:
A method should use the same defaults as the generic.
Here there might be justifiable exceptions, which will need careful documentation.
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 not to include a ... argument.
If a ... argument is supplied, some thought should be given to its position in the
argument sequence. Arguments which follow ... must be named in calls to the function, and
they must be named in full (partial matching is suppressed after ...). Formal arguments
before ... can be partially matched, and so may ‘swallow’ actual arguments intended for
.... Although it is commonplace to make the ... 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
foo <- function(object, ...) UseMethod("foo")
[Link] <- get("foo", pos = NULL, mode = "function")
(If the thus defined default method needs a ‘...’ added to its argument list, one can e.g.
use formals([Link]) <- c(formals([Link]), 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
[Link] <- base::foo
Appendix A: R (internal) programming miscellanea 72
C code compiled into R at build time can be called “directly” or via the .Internal in-
terface, which is very similar to the .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 ‘do_’ and return a SEXP. Via this table (R_FunTab in 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 .Internal interface,
or directly accessible in which case it is printed in R as .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 .Internal() as this is safer and in particular allows
for transparent handling of named and default arguments. For example, axis is defined as
axis <- function(side, at = NULL, labels = NULL, ...)
.Internal(axis(side, at, labels, ...))
However, for reasons of convenience and also efficiency (as there is some overhead in
using the .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, args and body return NULL for such objects.
The list of these “primitive” functions is subject to change: currently, it includes the
following.
1. “Special functions” which really are language elements, however exist as “primitive”
functions in R:
{ ( if for while repeat break next
return function quote [Link]
2. Basic operator s (i.e., functions usually not called as foo(a, b, ...)) for subsetting,
assignment, arithmetic and logic. These are the following 1-, 2-, and N -argument
functions:
[ [[ $
<- <<- [<- [[<- $<-
+ - * / ^ %% %*% %/%
< <= == != >= >
| || & && !
3. “Low level” 0- and 1-argument functions which belong to one of the following groups
of functions:
a. Basic mathematical functions with a single argument, i.e.,
sign abs
floor ceiling trunc
sqrt exp
cos sin tan
acos asin atan
cosh sinh tanh
acosh asinh atanh
Appendix A: R (internal) programming miscellanea 73
cumsum cumprod
cummax cummin
Im Re
Arg Conj Mod
Note however that the R function log has an optional named argument base, and
therefore is defined as
log <- function(x, base = exp(1)) {
if(missing(base))
.Internal(log(x))
else
.Internal(log(x, base))
}
in order to ensure that log(x = pi, base = 2) is identical to log(base = 2, x =
pi).
b. Functions rarely used outside of “programming” (i.e., mostly used inside other
functions), such as
nargs missing
interactive [Link]
.Primitive .Internal .External
symbol.C [Link]
globalenv [Link] unclass
(where xxx stands for almost 30 different notions, such as function, vector,
numeric, and so forth).
c. The programming and session management utilities
debug undebug trace untrace
browser [Link]
4. The following basic assignment and extractor functions
length length<-
class class<-
attr attr<-
attributes attributes<-
dim dim<-
dimnames dimnames<-
environment<-
5. The following few N -argument functions are “primitive” for efficiency reasons. Care is
taken in order to treat named arguments properly:
: ~ c list unlist
call [Link] expression substitute
UseMethod invisible
.C .Fortran .Call
When you (as R developer) add new functions to the R base (all the packages distributed
with R), be careful to check if make test-Specific or particularly, cd tests; make no-
[Link] still works (without interactive user intervention, and on a standalone com-
puter). If the new function, for example, accesses the Internet, or requires gui interaction,
please add its name to the “stop list” in ‘tests/[Link]’.
Appendix B: R coding standards 74
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 binary
(pre-built) versions of add-on packages, or at run time.
• Makeinfo version 4 is needed to build the Info files for the R manuals written in the
gnu Texinfo system. (Future distributions of R will contain the Info files.)
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 gnu Emacs 20: for gnu Emacs 21 use customization to
set the c-default-style to "bsd" and c-basic-offset to 4.)
;;; C
(add-hook ’c-mode-hook
(lambda () (c-set-style "bsd")))
;;; 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)))))
;;; Perl
(add-hook ’perl-mode-hook
(lambda () (setq perl-indent-level 4)))
(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.)
Appendix B: Function and variable index 76
. \source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
.C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 \sQuote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
.Call . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37, 45 \strong . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
.External . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37, 46 \synopsis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
.Fortran. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 \tabular. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
.Internal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 \title . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
.Primitive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72 \url . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
.[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 \usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
\value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
\var . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
\
\acronym. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 B
\alias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
\arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 bessel_i. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
\author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 bessel_j. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
\bold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 bessel_k. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
\cite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 bessel_y. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
\code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 beta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
\command. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 BLAS_LIBS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
\concept. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
\cr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 C
\deqn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
\describe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Calloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
\description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 CAR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
\details. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 CDR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
\dfn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 cgmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
\dontrun. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 choose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62, 63
\dontshow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 cPsort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
\dots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
\dQuote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
\email . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
22
22
D
\emph . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 defineVar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
\enumerate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 digamma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
\env . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 [Link]. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
\eqn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
\examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
\file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
\format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
E
\itemize. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 exp_rand. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
\kbd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 expm1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
\keyword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
\ldots . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
\link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 F
\method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 FALSE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
\name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 findInterval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
\note . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 findVar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
\option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 FLIBS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
\pkg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 fmax2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
\preformatted . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 fmin2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
\R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 fprec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
\references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Free . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
\samp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 fround . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
\section. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 fsign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
\seealso. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 ftrunc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Appendix B: Function and variable index 77
G R
gammafn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 R CMD build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
getAttrib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42 R CMD check . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
GetRNGstate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 R CMD config . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
R CMD Rd2dvi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
R CMD Rd2txt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
I R CMD Rdconv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
imax2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 R CMD Sd2Rd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
R CMD SHLIB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
imin2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
R_alloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
install . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
R_csort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
iPsort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
R_ExpandFileName . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
ISNA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47, 59
R_FINITE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
ISNAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47, 59
R_IsNaN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
R_isort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
R_LIBRARY_DIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
L R_max_col . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
LAPACK_LIBS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 R_NegInf. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
lbeta . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 R_PACKAGE_DIR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
lbfgsb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 R_PosInf. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
lchoose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62, 63 R_pow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
lgammafn. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 R_pow_di. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 R_qsort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
log1p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 R_qsort_I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
R_qsort_int . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
R_qsort_int_I . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
M R_rsort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
R_tmpnam. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
M_E . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 R_Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
M_PI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 Rdqagi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Rdqags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Realloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
N REprintf. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
NA_REAL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 REPROTECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
nmmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 REvprintf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
norm_rand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 revsort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
Rprintf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Rprof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
P rPsort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
rsort_with_index . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
pentagamma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Rvprintf. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
PKG_CFLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
PKG_CPPFLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
PKG_CXXFLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 S
PKG_FFLAGS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
PKG_LIBS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 S_alloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
prompt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 S_realloc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
PROTECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38 samin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
seed_in . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
PROTECT_WITH_INDEX . . . . . . . . . . . . . . . . . . . . . . . . . 40
seed_out. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
PutRNGstate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
setAttrib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
pythag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
setVar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
sign . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
symbol.C. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Q [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
qsort3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 system . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
qsort4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
Appendix B: Function and variable index 78
T UNPROTECT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
tetragamma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 UNPROTECT_PTR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
trigamma. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
TRUE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
V
vmaxget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
U vmaxset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
unif_rand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 vmmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Appendix B: Concept index 79
Concept index
A I
Allocating storage . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 IEEE special values. . . . . . . . . . . . . . . . . . . . . . . 47, 59
Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41 Indices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Inspecting R objects when debugging. . . . . . . . . . 55
integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
B Interfaces to compiled code . . . . . . . . . . . . . . . 30, 44
Bessel functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Interfacing C++ code . . . . . . . . . . . . . . . . . . . . . . . . . 35
Beta function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Building packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
L
C Lists and tables in documentation . . . . . . . . . . . . . 23
C++ code, interfacing . . . . . . . . . . . . . . . . . . . . . . . . . 35
Calling C from FORTRAN and vice versa . . . . . 60
Checking packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
M
Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Marking text in documentation . . . . . . . . . . . . . . . 22
CRAN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Mathematics in documentation . . . . . . . . . . . . . . . 24
CRAN submission . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 Memory allocation from C . . . . . . . . . . . . . . . . . . . . 57
Creating packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Method functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Creating shared objects . . . . . . . . . . . . . . . . . . . . . . 35 Missing values . . . . . . . . . . . . . . . . . . . . . . . . . . . 47, 59
Cross-references in documentation . . . . . . . . . . . . 23
cumulative hazard . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
N
D name spaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 Numerical analysis subroutines from C . . . . . . . . 61
DESCRIPTION file . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Numerical derivatives . . . . . . . . . . . . . . . . . . . . . . . . 51
Details of R types . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Distribution functions from C . . . . . . . . . . . . . . . . . 61
Documentation, writing . . . . . . . . . . . . . . . . . . . . . . 16 O
Dynamic loading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 Operating system access . . . . . . . . . . . . . . . . . . . . . . 30
optimization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
E
Error handling from C . . . . . . . . . . . . . . . . . . . . . . . 58 P
Error handling from FORTRAN . . . . . . . . . . . . . . 58
Package builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Evaluating R expressions from C . . . . . . . . . . . . . . 48
Package bundles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Package structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
F Package subdirectories . . . . . . . . . . . . . . . . . . . . . . . . 4
Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Finding variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Parsing R code from C . . . . . . . . . . . . . . . . . . . . . . . 53
Platform-specific documentation . . . . . . . . . . . . . . 25
G Printing from C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Printing from FORTRAN . . . . . . . . . . . . . . . . . . . . 60
Gamma function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Processing Rd format . . . . . . . . . . . . . . . . . . . . . . . . 26
Garbage collection . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Generic functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
H R
Handling lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 Random numbers in C . . . . . . . . . . . . . . . . . . . . 58, 61
Handling R objects in C . . . . . . . . . . . . . . . . . . . . . . 37 Registering native routines . . . . . . . . . . . . . . . . . . . 33
Appendix B: Concept index 80
S V
Setting variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 Version information from C . . . . . . . . . . . . . . . . . . . 68
Sort functions from C . . . . . . . . . . . . . . . . . . . . . . . . 67
vignettes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Submitting to CRAN . . . . . . . . . . . . . . . . . . . . . . . . 12
Sweave . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
T Z
Tidying R code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 Zero-finding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49