Movatterモバイル変換


[0]ホーム

URL:


Next:, Up:(dir)   [Contents][Index]

Writing R Extensions

This is a guide to extending R, describing the process of creatingR add-on packages, writing R documentation, R’s system andforeign language interfaces, and the RAPI.

This manual is for R, version 4.5.1 (2025-06-13).

Copyright © 1999–2025 R Core Team

Permission is granted to make and distribute verbatim copies of thismanual provided the copyright notice and this permission notice arepreserved on all copies.

Permission is granted to copy and distribute modified versions of thismanual under the conditions for verbatim copying, provided that theentire resulting derived work is distributed under the terms of apermission notice identical to this one.

Permission is granted to copy and distribute translations of this manualinto another language, under the above conditions for modified versions,except that this permission notice may be stated in a translationapproved by the R Core Team.

Table of Contents


Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

Acknowledgements

The contributions to early versions of this manual by Saikat DebRoy(who wrote the first draft of a guide to using.Call and.External) and Adrian Trapletti (who provided information on theC++ interface) are gratefully acknowledged.


Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

1 Creating R packages

Packages provide a mechanism for loading optional code, data anddocumentation as needed. The R distribution itself includes about 30packages.

In the following, we assume that you know thelibrary() command,including itslib.loc argument, and we also assume basicknowledge of theR CMD INSTALL utility. Otherwise, pleaselook at R’s help pages on

?library?INSTALL

before reading on.

For packages which contain code to be compiled, a computing environmentincluding a number of tools is assumed; the “R Installation andAdministration” manual describes what is needed for each OS.

Once a source package is created, it must be installed bythe commandR CMD INSTALL.SeeAdd-on packages inR Installation and Administration.

Other types of extensions are supported (but rare): SeePackage types.

Some notes on terminology complete this introduction. These will helpwith the reading of this manual, and also in describing conceptsaccurately when asking for help.

Apackage is a directory of files which extend R, asource package (the master files of a package), or a tarballcontaining the files of a source package, or aninstalledpackage, the result of runningR CMD INSTALL on a sourcepackage. On some platforms (notably macOS and ‘x86_64’ Windows)there are alsobinary packages, a zip file or tarball containingthe files of an installed package which can be unpacked rather thaninstalling from sources.

A package isnot1 alibrary. The latter is used in two senses in R documentation.

There are a number of well-defined operations on source packages.

The concept oflazy loading of code or data is mentioned atseveral points. This is part of the installation, always selected forR code but optional for data. When used the R objects of thepackage are created at installation time and stored in a database in theR directory of the installed package, being loaded into thesession at first use. This makes the R session start up faster anduse less (virtual) memory.(For technical details,seeLazy loading inR Internals.)

CRAN is a network of WWW sites holding the R distributionsand contributed code, especially R packages. Users of R areencouraged to join in the collaborative project and to submit their ownpackages toCRAN: current instructions are linked fromhttps://CRAN.R-project.org/banner.shtml#submitting.


Next:, Up:Creating R packages   [Contents][Index]

1.1 Package structure

The sources of an R package consist of a subdirectory containing thefilesDESCRIPTION andNAMESPACE, and the subdirectoriesR,data,demo,exec,inst,man,po,src,tests,tools andvignettes (some of which can be missing, but which should not beempty). The package subdirectory may also contain filesINDEX,configure,cleanup,LICENSE,LICENCE andNEWS. Other files such asINSTALL (for non-standardinstallation instructions),README/README.md2, orChangeLog will be ignored by R, but maybe useful to end users. The utilityR CMD build may add filesin abuild directory (but this should not be used for otherpurposes).

Except where specifically mentioned,3 packages should not containUnix-style ‘hidden’ files/directories (that is, those whose name startswith a dot).

TheDESCRIPTION andINDEX files are described in thesubsections below. TheNAMESPACE file is described in thesection onPackage namespaces.

The optional filesconfigure andcleanup are (Bourne)shell scripts which are, respectively, executed before and (if option--clean was given) after installation on Unix-alikes, seeConfigure and cleanup. The analogues on Windows areconfigure.win andcleanup.win. Since R 4.2.0 on Windows,configure.ucrt andcleanup.ucrt are supported and takeprecedence overconfigure.win andcleanup.win. They canhence be used to provide content specific toUCRT or Rtools42 and newer, if needed,but the support for.ucrt files may be removed in future whenbuilding packages from source on the older versions of R will no longerbe needed, and hence the files may be renamed back to.win.

For the conventions for filesNEWS andChangeLog in theGNU project seehttps://www.gnu.org/prep/standards/standards.html#Documentation.

The package subdirectory should be given the same name as the package.Because some file systems (e.g., those on Windows and by default onmacOS) are not case-sensitive, to maintain portability it is stronglyrecommended that case distinctions not be used to distinguish differentpackages. For example, if you have a package namedfoo, do notalso create a package namedFoo.

To ensure that file names are valid across file systems and supportedoperating systems, theASCII control characters as well as thecharacters ‘"’, ‘*’, ‘:’, ‘/’, ‘<’, ‘>’,‘?’, ‘\’, and ‘|’ are not allowed in file names. Inaddition, files with names ‘con’, ‘prn’, ‘aux’,‘clock$’, ‘nul’, ‘com1’ to ‘com9’, and ‘lpt1’to ‘lpt9’ after conversion to lower case and stripping possible“extensions” (e.g., ‘lpt5.foo.bar’), are disallowed. Also, filenames in the same directory must not differ only by case (see theprevious paragraph). In addition, the basenames of ‘.Rd’ files maybe used in URLs and so must beASCII and not contain%.For maximal portability filenames should only contain onlyASCII characters not excluded already (that isA-Za-z0-9._!#$%&+,;=@^(){}'[] — we exclude space as manyutilities do not accept spaces in file paths): non-English alphabeticcharacters cannot be guaranteed to be supported in all locales. Itwould be good practice to avoid the shell metacharacters(){}'[]$~:~ is also used as part of ‘8.3’ filenames onWindows. In addition, some applications on Windows can only work with pathnames of certain length, following an earlier limit in the Windows operatingsystem. Packages are normally distributed as tarballs, and these have a limiton path lengths. So, to be friendly to users who themselves may want to use arelatively long path where they extract the package, and for maximalportability, 100 bytes.

A source package if possible should not contain binary executable files:they are not portable, and a security risk if they are of theappropriate architecture.R CMD check will warn aboutthem4 unless they are listed (one filepath per line) in a fileBinaryFiles at the top level of the package. Note thatCRAN will not accept submissions containing binary fileseven if they are listed.

The R functionpackage.skeleton can help to create thestructure for a new package: see its help page for details.


Next:, Up:Package structure   [Contents][Index]

1.1.1 TheDESCRIPTION file

TheDESCRIPTION file contains basic information about the packagein the following format:

Package: pkgnameVersion: 0.5-1Date: 2015-01-01Title: My First Collection of FunctionsAuthors@R: c(person("Joe", "Developer", role = c("aut", "cre"),                     email = "Joe.Developer@some.domain.net",                     comment = c(ORCID = "nnnn-nnnn-nnnn-nnnn")),              person("Pat", "Developer", role = "aut"),              person("A.", "User", role = "ctb",                     email = "A.User@whereever.net"))Author: Joe Developer [aut, cre],  Pat Developer [aut],  A. User [ctb]Maintainer: Joe Developer <Joe.Developer@some.domain.net>Depends: R (>= 3.1.0), nlmeSuggests: MASSDescription: A (one paragraph) description of what  the package does and why it may be useful.License: GPL (>= 2)URL: https://www.r-project.org, http://www.another.urlBugReports: https://pkgname.bugtracker.url

The format is that of a version of a ‘Debian Control File’ (see the helpfor ‘read.dcf’ andhttps://www.debian.org/doc/debian-policy/ch-controlfields.html:R does not require encoding in UTF-8 and does not support commentsstarting with ‘#’). Fields start with anASCII nameimmediately followed by a colon: the value starts after the colon and aspace. Continuation lines (for example, for descriptions longer thanone line) start with a space or tab. Field names are case-sensitive:all those used by R are capitalized.

For maximal portability, theDESCRIPTION file should be writtenentirely inASCII — if this is not possible it must containan ‘Encoding’ field (see below).

Several optional fields takelogical values: these can bespecified as ‘yes’, ‘true’, ‘no’ or ‘false’:capitalized values are also accepted.

The ‘Package’, ‘Version’, ‘License’, ‘Description’,‘Title’, ‘Author’, and ‘Maintainer’ fields are mandatory,all other fields are optional. Fields ‘Author’ and‘Maintainer’ can be auto-generated from ‘Authors@R’, and maybe omitted if the latter is provided: however if they are notASCII we recommend that they are provided.

The mandatory ‘Package’ field gives the name of the package. Thisshould contain only (ASCII) letters, numbers and dot, have atleast two characters and start with a letter and not end in a dot. Ifit needs explaining, this should be done in the ‘Description’ field(and not the ‘Title’ field).

The mandatory ‘Version’ field gives the version of the package.This is a sequence of at leasttwo (and usually three)non-negative integers separated by single ‘.’ or ‘-’characters. The canonical form is as shown in the example, and aversion such as ‘0.01’ or ‘0.01.0’ will be handled as if itwere ‘0.1-0’. It isnot a decimal number, so for example0.9 < 0.75 since9 < 75.

The mandatory ‘License’ field is discussed in the next subsection.

The mandatory ‘Title’ field should give ashort descriptionof the package. Some package listings may truncate the title to 65characters. It should usetitle case (that is, use capitals forthe principal words:tools::toTitleCase can help you with this),not use any markup, not have any continuation lines, and not end in aperiod (unless part of …). Do not repeat the package name: it isoften used prefixed by the name. Refer to other packages and externalsoftware in single quotes, and to book titles (and similar) in doublequotes.

The mandatory ‘Description’ field should give acomprehensive description of what the package does. One can useseveral (complete) sentences, but only one paragraph. It should beintelligible to all the intended readership (e.g. for aCRANpackage to allCRAN users). It is good practice not to startwith the package name, ‘This package’ or similar. As with the‘Title’ field, double quotes should be used for quotations(including titles of books and articles), and single quotes fornon-English usage, including names of other packages and externalsoftware. This field should also be used for explaining the packagename if necessary. URLs should be enclosed in angle brackets, e.g.‘<https://www.r-project.org>’: see alsoSpecifying URLs.

The mandatory ‘Author’ field describes who wrotethepackage. It is a plain text field intended for human readers, but notfor automatic processing (such as extracting the email addresses of alllisted contributors: for that use ‘Authors@R’). Note that allsignificant contributors must be included: if you wrote an R wrapperfor the work of others included in thesrc directory, you are notthe sole (and maybe not even the main) author.

The mandatory ‘Maintainer’ field should give asingle namefollowed by avalid (RFC 2822) email address in angle brackets. Itshould not end in a period or comma. This field is what is reported bythemaintainer function and used bybug.report. For aCRAN package it should be aperson, not a mailing listand not a corporate entity: do ensure that it is valid and will remainvalid for the lifetime of the package.

Note that thedisplay name (the part before the address in anglebrackets) should be enclosed in double quotes if it containsnon-alphanumeric characters such as comma or period. (The currentstandard, RFC 5322, allows periods but RFC 2822 did not.)

Both ‘Author’ and ‘Maintainer’ fields can be omitted if asuitable ‘Authors@R’ field is given. This field can be used toprovide a refined and machine-readable description of the package“authors” (in particular specifying their preciseroles),via suitable R code. It should create an object of class"person", by either a call toperson or a series of calls(one per “author”) concatenated byc(): see the exampleDESCRIPTION file above. The roles can include ‘"aut"’(author) for full authors, ‘"cre"’ (creator) for the packagemaintainer, and ‘"ctb"’ (contributor) for other contributors,‘"cph"’ (copyright holder, which should be the legal name for aninstitution or corporate body), among others. See?person formore information. Note that no role is assumed by default.Auto-generated package citation information takes advantage of thisspecification. The ‘Author’ and ‘Maintainer’ fields areauto-generated from it if needed when building5 or installing.Note that for CRAN submissions, providing ‘Authors@R’ is required,and providingORCID orROR identifiers (seehttps://orcid.org/ andhttps://ror.org/) where possible isstrongly encouraged.

An optional ‘Copyright’ field can be used where the copyrightholder(s) are not the authors. If necessary, this can refer to aninstalled file: the convention is to use fileinst/COPYRIGHTS.

The optional ‘Date’ field gives therelease date of thecurrent version of the package. Using the ‘yyyy-mm-dd’ format ofthe ISO 8601 standard is strongly recommended6.

The ‘Depends’, ‘Imports’, ‘Suggests’, ‘Enhances’,‘LinkingTo’ and ‘Additional_repositories’ fields are discussedin a later subsection.

Dependencies external to the R system should be listed in the‘SystemRequirements’ field, possibly amplified in a separateREADME file. This includes specifying a non-default C++ standardand the need for GNUmake.

The ‘URL’ field may give a list ofURLsseparated by commas or whitespace, for example the homepage of theauthor or a page where additional material describing the software canbe found. TheseURLs are converted to active hyperlinks inCRAN package listings. SeeSpecifying URLs.

The ‘BugReports’ field may contain a singleURL to whichbug reports about the package should be submitted. ThisURLwill be used bybug.report instead of sending an email to themaintainer. A browser is opened for a ‘http://’ or ‘https://URL. To specify another email address for bug reports, use‘Contact’ instead: howeverbug.report will try to extract anemail address (preferably from a ‘mailto:’ URL or enclosed in anglebrackets) from ‘BugReports’.

Base and recommended packages (i.e., packages contained in the Rsource distribution or available fromCRAN and recommended tobe included in every binary distribution of R) have a ‘Priority’field with value ‘base’ or ‘recommended’, respectively. Thesepriorities must not be used by other packages.

A ‘Collate’ field can be used for controlling the collation orderfor the R code files in a package when these are processed forpackage installation. The default is to collate according to the‘C’ locale. If present, the collate specification must listall R code files in the package (taking possible OS-specificsubdirectories into account, seePackage subdirectories) as awhitespace separated list of file paths relative to theRsubdirectory.Paths containing white space or quotes need to be quoted. AnOS-specific collation field (‘Collate.unix’ or‘Collate.windows’) will be used in preference to ‘Collate’.

The ‘LazyData’ logical field controls whether the R datasets uselazy-loading. A ‘LazyLoad’ field was used in versions prior to2.14.0, but now is ignored.

The ‘KeepSource’ logical field controls if the package code is sourcedusingkeep.source = TRUE orFALSE: it might be neededexceptionally for a package designed to always be used withkeep.source = TRUE.

The ‘ByteCompile’ logical field controls if the package R code is tobe byte-compiled on installation: the default is to byte-compile. Thiscan be overridden by installing with flag--no-byte-compile.

The ‘UseLTO’ logical field is used to indicate if source code inthe package7 is to becompiled with Link-Time Optimization (seeUsing Link-time Optimization) if R was installed with--enable-lto (defaulttrue) or--enable-lto=R (default false) (or onWindows8 ifLTO_OPT is set inMkRules). This can be overridden by theflags--use-LTO and--no-use-LTO.LTO is said to givemost size and performance improvements for large and complex (heavilytemplated) C++ projects.

The ‘StagedInstall’ logical field controls if package installationis ‘staged’, that is done to a temporary location and moved to the finallocation when successfully completed. This field was introduced in R3.6.0 and is true by default: it is considered to be a temporary measurewhich may be withdrawn in future.

The ‘ZipData’ logical field has been ignored since R 2.13.0.

The ‘Biarch’ logical field is used on Windows to select theINSTALL option--force-biarch for this package. Notcurrently relevant.

The ‘BuildVignettes’ logical field can be set to a false value tostopR CMD build from attempting to build the vignettes, aswell as preventing9R CMD check from testingthis. This should only be used exceptionally, for example if the PDFsinclude large figures which are not part of the package sources (andhence only in packages which do not have an Open Source license).

The ‘VignetteBuilder’ field names (in a comma-separated list)packages that provide an engine for building vignettes. These mayinclude the current package, or ones listed in ‘Depends’,‘Suggests’ or ‘Imports’. Theutils package is alwaysimplicitly appended. SeeNon-Sweave vignettes for details. Notethat if, for example, a vignette has engine ‘knitr::rmarkdown’,thenknitr provides the engine but bothknitr andrmarkdown are needed for using it, soboth thesepackages need to be in the ‘VignetteBuilder’ field and at leastsuggested (asrmarkdown is only suggested byknitr, andhence not available automatically along with it). Many packages usingknitr also need the packageformatR which itsuggests and so the user package needs to do so too and include this in‘VignetteBuilder’.

If theDESCRIPTION file is not entirely inASCII itshould contain an ‘Encoding’ field specifying an encoding. This isused as the encoding of theDESCRIPTION file itself and of theR andNAMESPACE files, and as the default encoding of.Rd files. The examples are assumed to be in this encoding whenrunningR CMD check, and it is used for the encoding of theCITATION file. Only encoding nameslatin1 andandUTF-8 are known to be portable. (Do not specify an encodingunless one is actually needed: doing so makes the packagelessportable. If a package has a specified encoding, you should runR CMD build etc in a locale using that encoding.)

The ‘NeedsCompilation’ field should be set to"yes" if thepackage contains native code which needs to be compiled, otherwise"no" (whenthe package could be installed from source on any platform withoutadditional tools). This is used byinstall.packages(type ="both") in R >= 2.15.2 on platforms where binary packages are thenorm: it is normally set byR CMD build or the repositoryassuming compilation is required if and only if the package has asrc directory.

The ‘OS_type’ field specifies the OS(es) for which thepackage is intended. If present, it should be one ofunix orwindows, and indicates that the package can only be installedon a platform with ‘.Platform$OS.type’ having that value.

The ‘Type’ field specifies the type of the package:seePackage types.

One can add subject classifications for the content of the package usingthe fields ‘Classification/ACM’ or ‘Classification/ACM-2012’(using the Computing Classification System of the Association forComputing Machinery,https://www.acm.org/publications/class-2012; the former refersto the 1998 version), ‘Classification/JEL’ (the Journal of EconomicLiterature Classification System,https://www.aeaweb.org/econlit/jelCodes.php, or‘Classification/MSC’ or ‘Classification/MSC-2010’ (theMathematics Subject Classification of the American Mathematical Society,https://mathscinet.ams.org/msc/msc2010.html; the former refers to the 2000 version).The subject classifications should be comma-separated lists of therespective classification codes, e.g., ‘Classification/ACM: G.4,H.2.8, I.5.1’.

A ‘Language’ field can be used to indicate if the packagedocumentation is not in English: this should be a comma-separated listof standard (not private use or grandfathered)IETF language tags ascurrently defined by RFC 5646(https://www.rfc-editor.org/rfc/rfc5646, see alsohttps://en.wikipedia.org/wiki/IETF_language_tag), i.e., uselanguage subtags which in essence are 2-letter ISO 639-1(https://en.wikipedia.org/wiki/ISO_639-1) or 3-letter ISO639-3 (https://en.wikipedia.org/wiki/ISO_639-3) languagecodes.

An ‘RdMacros’ field can be used to hold a comma-separated list ofpackages from which the current package will importRd macrodefinitions. These package should also be listed in ‘Imports’(or ‘Depends’). The macros in these packages will beimported after the system macros, in theorder listed in the ‘RdMacros’ field, before any macro definitionsin the current package are loaded. Macro definitions in individual.Rd files in theman directory are loaded last, and arelocal to later parts of that file. In case of duplicates, the lastloaded definition will be used.10 BothR CMDRd2pdf andR CMD Rdconv have an optional flag--RdMacros=pkglist. The option is also a comma-separated listof package names, and has priority over the value given inDESCRIPTION. Packages usingRd macros should depend onR 3.2.0 or later.

Note: There should be no ‘Built’ or ‘Packaged’ fields, as these areadded by the package management tools.

There is no restriction on the use of other fields not mentioned here(but using other capitalizations of these field names would causeconfusion). FieldsNote,Contact (for contacting theauthors/developers11) andMailingList are in commonuse. Some repositories (includingCRAN and R-forge) add theirown fields.


Next:, Previous:, Up:Package structure   [Contents][Index]

1.1.2 Licensing

Licensing for a package which might be distributed is an important butpotentially complex subject.

It is very important that you include license information! Otherwise,it may not even be legally correct for others to distribute copies ofthe package, let alone use it.

The package management tools use the concept of‘free or open source software’(FOSS, e.g.,https://en.wikipedia.org/wiki/FOSS)licenses: the idea being that some users of R and its packages wantto restrict themselves to such software. Others need to ensure thatthere are no restrictions stopping them using a package, e.g.forbidding commercial or military use. It is a central tenet ofFOSSsoftware that there are no restrictions on users nor usage.

Do not use the ‘License’ field for information on copyrightholders: if needed, use a ‘Copyright’ field.

The mandatory ‘License’ field in theDESCRIPTION file shouldspecify the license of the package in a standardized form. Alternativesare indicatedvia vertical bars. Individual specifications mustbe one of

  • One of the “standard” short specifications
    GPL-2 GPL-3 LGPL-2 LGPL-2.1 LGPL-3 AGPL-3 Artistic-2.0BSD_2_clause BSD_3_clause MIT

    as made availableviahttps://www.R-project.org/Licenses/ andcontained in subdirectoryshare/licenses of the R source or homedirectory.

  • The names or abbreviations of other licenses contained in the licensedata base in fileshare/licenses/license.db in the R source orhome directory, possibly (for versioned licenses) followed by a versionrestriction of the form ‘(opv)’ with ‘op’ one ofthe comparison operators ‘<’, ‘<=’, ‘>’, ‘>=’,‘==’, or ‘!=’ and ‘v’ a numeric version specification(strings of non-negative integers separated by ‘.’), possiblycombinedvia,’ (see below for an example). For versionedlicenses, one can also specify the name followed by the version, orcombine an existing abbreviation and the version with a ‘-’.

    AbbreviationsGPL andLGPL are ambiguous andusually12 taken to mean any version of the license: but it is betternot to use them.

  • One of the strings ‘file LICENSE’ or ‘file LICENCE’ referringto a file namedLICENSE orLICENCE in the package (sourceand installation) top-level directory.
  • The string ‘Unlimited’, meaning that there are no restrictions ondistribution or use other than those imposed by relevant laws (includingcopyright laws).

Multiple licences can be specified separated by ‘|’ (surrounded byspaces) in which case the user can choose any of the alternatives.

If a package licenserestricts a base license (where permitted,e.g., using GPL-3 or AGPL-3 with an attribution clause), the additionalterms should be placed in fileLICENSE (orLICENCE), andthe string ‘+ file LICENSE’ (or ‘+ file LICENCE’,respectively) should be appended to the corresponding individual licensespecification (preferably with the ‘+’ surrounded by spaces). Notethat several commonly used licenses do not permit restrictions: thisincludes GPL-2 and hence any specification which includes it.

Examples of standardized specifications include

License: GPL-2License: LGPL (>= 2.0, < 3) | Mozilla Public LicenseLicense: GPL-2 | file LICENCELicense: GPL (>= 2) | BSD_3_clause + file LICENSELicense: Artistic-2.0 | AGPL-3 + file LICENSE

Please note in particular that “Public domain” is not a valid license,since it is not recognized in some jurisdictions.

Please ensure that the license you choose also covers any dependencies(including system dependencies) of your package: it is particularlyimportant that any restrictions on the use of such dependencies areevident to people reading yourDESCRIPTION file.

Fields ‘License_is_FOSS’ and ‘License_restricts_use’ may beadded by repositories where information cannot be computed from the nameof the license. ‘License_is_FOSS: yes’ is used for licenses whichare known to beFOSS, and ‘License_restricts_use’ can have values‘yes’ or ‘no’ if theLICENSE file is known to restrictusers or usage, or known not to. These are used by, e.g., theavailable.packages filters.

The optional fileLICENSE/LICENCE contains a copy of thelicense of the package. To avoid any confusion only include such a fileif it is referred to in the ‘License’ field of theDESCRIPTION file.

Whereas you should feel free to include a license file in yoursource distribution, please do not arrange toinstall yetanother copy of theGNUCOPYING orCOPYING.LIBfiles but refer to the copies onhttps://www.R-project.org/Licenses/ and included in the Rdistribution (in directoryshare/licenses). Since files namedLICENSE orLICENCEwill be installed, do not usethese names for standard license files. To include comments about thelicensing rather than the body of a license, use a file named somethinglikeLICENSE.note.

A few “standard” licenses are rather license templates which needadditional information to be completedvia+ file LICENSE’(with the ‘+’ surrounded by spaces). Where the additionalinformation is ‘COPYRIGHT HOLDER’, this must give the actual legalentities (not something vague like ‘Name-of-package authors’): if morethan one they should be listed in decreasing order of contribution.


Next:, Previous:, Up:Package structure   [Contents][Index]

1.1.3 Package Dependencies

The ‘Depends’ field gives a comma-separated list of package nameswhich this package depends on. Those packages will be attached beforethe current package whenlibrary orrequire is called.Each package name may be optionally followed by a comment in parenthesesspecifying a version requirement. The comment should contain acomparison operator, whitespace and a valid version number,e.g. ‘MASS (>= 3.1-20)’.

The ‘Depends’ field can also specify a dependence on a certainversion of R — e.g., if the package works only with R version4.0.0 or later, include ‘R (>= 4.0)’ in the ‘Depends’field. (As here, trailing zeroes can be dropped and it is recommendedthat they are.) You can also require a certain SVN revision for R-develor R-patched, e.g. ‘R (>= 2.14.0), R (>= r56550)’ requires aversion later than R-devel of late July 2011 (including releasedversions of 2.14.0).

It makes no sense to declare a dependence onR without a versionspecification, nor on the packagebase: this is an R packageand packagebase is always available.

A package or ‘R’ can appear more than once in the ‘Depends’field, for example to give upper and lower bounds on acceptableversions.

It is inadvisable to use a dependence on R with patch level (the thirddigit) other than zero. Doing so with packages which others depend onwill cause the other packages to become unusable under earlier versionsin the series, and e.g. versions 4.x.1 are widely used throughout theNorthern Hemisphere academic year.

Bothlibrary and the R package checking facilities use thisfield: hence it is an error to use improper syntax or misuse the‘Depends’ field for comments on other software that might beneeded. The RINSTALL facilities check if the version ofR used is recent enough for the package being installed, and the listof packages which is specified will be attached (after checking versionrequirements) before the current package.

The ‘Imports’ field lists packages whose namespaces are importedfrom (as specified in theNAMESPACE file) but which do not needto be attached. Namespaces accessed by the ‘::’ and ‘:::’operators must be listed here, or in ‘Suggests’ or ‘Enhances’(see below). Ideally this field will include all the standard packagesthat are used, and it is important to include S4-using packages (astheir class definitions can change and theDESCRIPTION file isused to decide which packages to re-install when this happens).Packages declared in the ‘Depends’ field should not also be in the‘Imports’ field. Version requirements can be specified and arechecked when the namespace is loaded.

The ‘Suggests’ field uses the same syntax as ‘Depends’ andlists packages that are not necessarily needed. This includes packagesused only in examples, demos, tests or vignettes (seeWriting package vignettes), and packages loaded in the body of functions. E.g.,suppose an example13 frompackagefoo uses a dataset from packagebar. Then it is notnecessary to havebar to usefoo unless one wants to executeall the examples: it is useful to havebar, butnot necessary. Version requirements can be specified but should bechecked by the code which uses the package.

Finally, the ‘Enhances’ field lists packages “enhanced” by thepackage at hand, e.g., by providing methods for classes from thesepackages, or ways to handle objects from these packages (so severalpackages have ‘Enhances: chron’ because they can handle datetimeobjects fromchron even though they prefer R’s nativedatetime functions). Version requirements can be specified, but arecurrently not used. Such packages cannot be required to check thepackage: any tests which use them must be conditional on the presenceof the package. (If your tests use e.g. a dataset from anotherpackage it should be in ‘Suggests’ and not ‘Enhances’.)

The general rules are

  • A package should be listed in only one of these fields.
  • Packages whose namespace only is needed to load the package usinglibrary(pkgname) should be listed in the ‘Imports’ fieldand not in the ‘Depends’ field. Packages listed inimportorimportFrom directives in theNAMESPACE file shouldalmost always be in ‘Imports’ and not ‘Depends’.
  • Packages that need to be attached to successfully load the package usinglibrary(pkgname) must be listed in the ‘Depends’field.
  • All packages that are needed14 to successfully runR CMD check on thepackage must be listed in one of ‘Depends’ or ‘Suggests’ or‘Imports’. Packages used to run examples or tests conditionally(e.g.viaif(require(pkgname))) should be listedin ‘Suggests’ or ‘Enhances’. (This allows checkers to ensurethat all the packages needed for a complete check are installed.)
  • Packages needed to use datasets from the package should be in‘Imports’: this includes those needed to define S4 classes used.

In particular, packages providing “only” data for examples, demos orvignettes should be listed in ‘Suggests’ rather than ‘Depends’in order to make lean installations possible.

Version dependencies in the ‘Depends’ and ‘Imports’ fields areused bylibrary when it loads the package, andinstall.packages checks versions for the ‘Depends’,‘Imports’ and (fordependencies = TRUE) ‘Suggests’fields.

It is important that the information in these fields is complete andaccurate: it is for example used to compute which packages depend on anupdated package and which packages can safely be installed in parallel.

This scheme was developed before all packages had namespaces (R2.14.0 in October 2011), and good practice changed once that was inplace.

Field ‘Depends’ should nowadays be used rarely, only for packageswhich are intended to be put on the search path to make their facilitiesavailable to the end user (and not to the package itself): for exampleit makes sense that a user of packagelatticeExtra would wantthe functions of packagelattice made available.

Almost always packages mentioned in ‘Depends’ should also beimported from in theNAMESPACE file: this ensures that any neededparts of those packages are available when some other package importsthe current package.

The ‘Imports’ field should not contain packages which are notimported from (via theNAMESPACE file or:: or::: operators), as all the packages listed in that field need tobe installed for the current package to be installed. (This is checkedbyR CMD check.)

R code in the package should calllibrary orrequireonly exceptionally. Such calls are never needed for packages listed in‘Depends’ as they will already be on the search path. It used tobe common practice to userequire calls for packages listed in‘Suggests’ in functions which used their functionality, butnowadays it is better to access such functionalityvia::calls.

A package that wishes to make use of header files in other packages tocompile its C/C++ code needs to declare them as a comma-separated listin the field ‘LinkingTo’ in theDESCRIPTION file. Forexample

LinkingTo: link1, link2

The ‘LinkingTo’ field can have a version requirement which ischecked at installation.

Specifying a package in ‘LinkingTo’ suffices if these are C/C++headers containing source code or static linking is done atinstallation: the packages do not need to be (and usually should not be)listed in the ‘Depends’ or ‘Imports’ fields. This includesCRAN packageBH and almost all users ofRcppArmadillo andRcppEigen. Note that‘LinkingTo’ applies only to installation: if a packages wishes touse headers to compile code in tests or vignettes the package providingthem needs to be listed in ‘Suggests’ or perhaps ‘Depends’.

For another use of ‘LinkingTo’ seeLinking to native routines in other packages.

The ‘Additional_repositories’ field is a comma-separated list ofrepository URLs where the packages named in the other fields may befound. It is currently used byR CMD check to check that thepackages can be found, at least as source packages (which can beinstalled on any platform).


1.1.3.1 Suggested packages

Note that someone wanting to run the examples/tests/vignettes may nothave a suggested package available (and it may not even be possible toinstall it for that platform). The recommendation used to be to maketheir use conditionalviaif(require("pkgname")):this is OK if that conditioning is done in examples/tests/vignettes,although usingif(requireNamespace("pkgname")) ispreferred, if possible.

However, usingrequire for conditioningin package code isnot good practice as it alters the search path for the rest of thesession and relies on functions in that package not being masked byotherrequire orlibrary calls. It is better practice touse code like

   if (requireNamespace("rgl", quietly = TRUE)) {      rgl::plot3d(...)   } else {      ## do something else not involving rgl.   }

Note the use ofrgl:: as that object would not necessarily bevisible (and if it is, it need not be the one from that namespace:plot3d occurs in several other packages). If the intention is togive an error if the suggested package is not available, simply usee.g.rgl::plot3d.

If the conditional code producesprint output, functionwithAutoprint can be useful.

Note that the recommendation to use suggested packages conditionally intests does also apply to packages used to manage test suites: anotorious example wastestthat which in version 1.0.0 containedillegal C++ code and hence could not be installed on standards-compliantplatforms.

Some people have assumed that a ‘recommended’ package in ‘Suggests’can safely be used unconditionally, but this is not so. (R can beinstalled without recommended packages, and which packages are‘recommended’ may change.)

As noted above, packages in ‘Enhancesmust be usedconditionally and hence objects within them should always be accessedvia::.

On most systems,R CMD check can be run with only thosepackages declared in ‘Depends’ and ‘Imports’ by settingenvironment variable_R_CHECK_DEPENDS_ONLY_=true, whereas setting_R_CHECK_SUGGESTS_ONLY_=true also allows suggested packages, butnot those in ‘Enhances’ nor those not mentioned in theDESCRIPTION file. It is recommended that a package is checkedwith each of these set, as well as with neither.

WARNING: Be extremely careful if you do things which would berun at installation time depending on whether suggested packages areavailable or not—this includes top-level code in R code files,.onLoad functions and the definitions of S4 classes and methods.The problem is that once a namespace of a suggested package is loaded,references to it may be captured in the installed package (most commonlyin S4 methods), but the suggested package may not be available when theinstalled package is used (which especially for binary packages might beon a different machine). Even worse, the problems might not be confinedto your package, for the namespaces of your suggested packages will alsobe loaded whenever any package which imports yours is installed and somay be captured there.


Next:, Previous:, Up:Package structure   [Contents][Index]

1.1.4 TheINDEX file

The optional fileINDEX contains a line for each sufficientlyinteresting object in the package, giving its name and a description(functions such as print methods not usually called explicitly might notbe included). Normally this file is missing and the correspondinginformation is automatically generated from the documentation sources(usingtools::Rdindex()) when installing from source.

The file is part of the information given bylibrary(help =pkgname).

Rather than editing this file, it is preferable to put customizedinformation about the package into an overview help page(seeDocumenting packages) and/or a vignette (seeWriting package vignettes).


Next:, Previous:, Up:Package structure   [Contents][Index]

1.1.5 Package subdirectories

TheR subdirectory contains R code files, only. The codefiles to be installed must start with anASCII (lower or uppercase) letter or digit and have one of the extensions15.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 usingsource(), soR objects must be created by assignments. Note that there need be noconnection between the name of the file and the R objects created byit. Ideally, the R code files should only directly assign Robjects and definitely should not call functions with side effects suchasrequire andoptions. If computations are required tocreate objects these can use code ‘earlier’ in the package (see the‘Collate’ field) plus functions in the ‘Depends’ packagesprovided that the objects created do not depend on those packages exceptvia namespace imports.

Extreme care is needed if top-level computations are made to depend onavailability or not of other packages. In particular this applies tosetMethods andsetClass calls. Nor should they depend onthe availability of external resources such as downloads.

Two exceptions are allowed: if theR subdirectory contains a filesysdata.rda (a saved image of one or more R objects: pleaseuse suitable compression as suggested bytools::resaveRdaFiles,and see also the ‘SysDataCompressionDESCRIPTION field.)this will be lazy-loaded into the namespace environment – this isintended for system datasets that are not intended to be user-accessibleviadata. Also, files ending in ‘.in’ will beallowed in theR directory to allow aconfigure script togenerate suitable files.

OnlyASCII characters (and the control characters tab,form feed,LF andCR) should be used in code files. Other characters areaccepted in comments16, but then the comments may notbe readable in e.g. a UTF-8 locale. Non-ASCII characters inobject names will normally17 fail when the package is installed. Any byte willbe allowed in a quoted character string but ‘\uxxxx’ escapes shouldbe used for non-ASCII characters. However,non-ASCII character strings may not be usable in some localesand may display incorrectly in others.

Various R functions in a package can be used to initialize andclean up. SeeLoad hooks.

Theman subdirectory should contain (only) documentation filesfor the objects in the package inR documentation (Rd) format.The documentation filenames must start with anASCII (lower orupper case) letter or digit and have the extension.Rd (thedefault) or.rd. Further, the names must be valid in‘file://’ URLs, which means18they must be entirelyASCII and not contain ‘%’.SeeWriting R documentation files, for more information. Note thatall user-level objects in a package should be documented; if a packagepkg contains user-level objects which are for “internal” useonly, it should provide a filepkg-internal.Rd whichdocuments all such objects, and clearly states that these are not meantto be called by the user. See e.g. the sources for packagegridin the R distribution. Note that packages which use internal objectsextensively should not export those objects from their namespace, whenthey do not need to be documented (seePackage namespaces).

Having aman directory containing no documentation files may givean installation error.

Theman subdirectory may contain a subdirectory namedmacros;this will contain source for user-defined Rd macros.(SeeUser-defined macros.) These use the Rd format, but maynot contain anything but macro definitions, comments and whitespace.

TheR andman subdirectories may contain OS-specificsubdirectories namedunix orwindows.

The sources and headers for the compiled code are insrc, plusoptionally a fileMakevars orMakefile (or for use onWindows, with extension.win or.ucrt). When a package isinstalled usingR CMD INSTALL,make is used to controlcompilation and linking into a shared object for loading into R.There are defaultmake variables and rules for this(determined when R is configured and recorded inR_HOME/etcR_ARCH/Makeconf), providing support for C,C++, fixed- or free-form Fortran, Objective C and ObjectiveC++19 with associated extensions.c,.cc or.cpp,.f,.f90 or.f95,20.m, and.mm, respectively. We recommend using.hfor headers, also for C++21 or Fortran include files. (Use of extension.C for C++ is no longer supported.) Files in thesrcdirectory should not be hidden (start with a dot), and hidden files willunder some versions of R be ignored.

It is not portable (and may not be possible at all) to mix all theselanguages in a single package. Because R itself uses it, we know thatC and fixed-form Fortran can be used together, and mixing C, C++ andFortran usually work for the platform’s native compilers.

If your code needs to depend on the platform there are certain defineswhich can be used in C or C++. On all Windows builds (even 64-bit ones)‘_WIN32’ will be defined: on 64-bit Windows builds also‘_WIN64’. For Windows on ARM, test for ‘_M_ARM64’ or both‘_WIN32’ and ‘__aarch64__’. On macOS ‘__APPLE__’ isdefined22; for an ‘Apple Silicon’ platform, testfor both ‘__APPLE__’ and ‘__arm64__’.

The default rules can be tweaked by setting macros23 in a filesrc/Makevars (seeUsingMakevars). Note that this mechanismshould be general enough to eliminate the need for a package-specificsrc/Makefile. If such a file is to be distributed, considerablecare is needed to make it general enough to work on all R platforms.If it has any targets at all, it should have an appropriate first targetnamed ‘all’ and a (possibly empty) target ‘clean’ whichremoves all files generated by runningmake (to be used by‘R CMD INSTALL --clean’ and ‘R CMD INSTALL --preclean’).There are platform-specific file names on Windows:src/Makevars.win takes precedence oversrc/Makevars andsrc/Makefile.win must be used. Since R 4.2.0,src/Makevars.ucrt takes precedence oversrc/Makevars.win andsrc/Makefile.ucrt takes precedenceoversrc/Makefile.win.src/Makevars.ucrt andsrc/Makefile.ucrt will be ignored by earlier versions of R, andhence can be used to provide content specific toUCRT or Rtools42 and newer,but the support for.ucrt files may be removed in the future whenbuilding packages from source on the older versions of R will no longerbe needed, and hence the files may be renamed back to.win.Somemake programsrequire makefiles to have a complete final line, including a newline.

A few packages use thesrc directory for purposes other thanmaking a shared object (e.g. to create executables). Such packagesshould have filessrc/Makefile andsrc/Makefile.win orsrc/Makefile.ucrt (unless intended for only Unix-alikes or onlyWindows). Note that on Unix such makefiles are included afterR_HOME/etc/R_ARCH/Makeconf so all the usual Rmacros and make rules are available – for example C compilation will bydefault use the C compiler and flags with which R wasconfigured. This also applies on Windows as from R 4.3.0: packagesintended to be used with earlier versions should include that filethemselves.

The order of inclusion of makefiles for a package which doesnot have asrc/Makefile file is

Unix-alikeWindows
src/Makevarssrc/Makevars.ucrt,src/Makevars.win
R_HOME/etc/R_ARCH/MakeconfR_HOME/etc/R_ARCH/Makeconf
R_MAKEVARS_SITE,R_HOME/etc/R_ARCH/Makevars.siteR_MAKEVARS_SITE,R_HOME/etc/R_ARCH/Makevars.site
R_HOME/share/make/shlib.mkR_HOME/share/make/winshlib.mk
R_MAKEVARS_USER, ~/.R/Makevars-platform, ~/.R/MakevarsR_MAKEVARS_USER, ~/.R/Makevars.ucrt, ~/.R/Makevars.win64, ~/.R/Makevars.win

For those which do, it is

R_HOME/etc/R_ARCH/MakeconfR_HOME/etc/R_ARCH/Makeconf
R_MAKEVARS_SITE,R_HOME/etc/R_ARCH/Makevars.siteR_MAKEVARS_SITE,R_HOME/etc/R_ARCH/Makevars.site
src/Makefilesrc/Makefile.ucrt,src/Makefile.win
R_MAKEVARS_USER, ~/.R/Makevars-platform, ~/.R/MakevarsR_MAKEVARS_USER, ~/.R/Makevars.ucrt, ~/.R/Makevars.win64, ~/.R/Makevars.win

Items in capitals are environment variables: those separated by commasare alternatives looked for in the order shown.

In very special cases packages may create binary files other than theshared objects/DLLs in thesrc directory. Such files will not beinstalled in a multi-architecture setting sinceR CMD INSTALL--libs-only is used to merge multiple sub-architectures and it onlycopies shared objects/DLLs. If a package wants to install otherbinaries (for example executable programs), it should provide an Rscriptsrc/install.libs.R which will be run as part of theinstallation in thesrc build directoryinstead of copyingthe shared objects/DLLs. The script is run in a separate Renvironment containing the following variables:R_PACKAGE_NAME(the name of the package),R_PACKAGE_SOURCE (the path to thesource directory of the package),R_PACKAGE_DIR (the path of thetarget installation directory of the package),R_ARCH (thearch-dependent part of the path, often empty),SHLIB_EXT (theextension of shared objects) andWINDOWS (TRUE on Windows,FALSE elsewhere). Something close to the default behavior couldbe replicated with the followingsrc/install.libs.R file:

files <- Sys.glob(paste0("*", SHLIB_EXT))dest <- file.path(R_PACKAGE_DIR, paste0('libs', R_ARCH))dir.create(dest, recursive = TRUE, showWarnings = FALSE)file.copy(files, dest, overwrite = TRUE)if(file.exists("symbols.rds"))    file.copy("symbols.rds", dest, overwrite = TRUE)

On the other hand, executable programs could be installed along thelines of

execs <- c("one", "two", "three")if(WINDOWS) execs <- paste0(execs, ".exe")if ( any(file.exists(execs)) ) {  dest <- file.path(R_PACKAGE_DIR,  paste0('bin', R_ARCH))  dir.create(dest, recursive = TRUE, showWarnings = FALSE)  file.copy(execs, dest, overwrite = TRUE)}

Note the use of architecture-specific subdirectories ofbin whereneeded. (Executables should installed under abin directory andnot underlibs. It is good practice to check that they can beexecuted as part of the installation script, so a broken package is notinstalled.)

Thedata subdirectory is for data files: SeeData in packages.

Thedemo subdirectory is for R scripts (for runningviademo()) that demonstrate some of the functionality of thepackage. Demos may be interactive and are not checkedautomatically24, soif testing is desired use code in thetests directory to achievethis. The script files must start with a (lower or upper case) letterand have one of the extensions.R or.r. If present, thedemo subdirectory should also have a00Index file with oneline for each demo, giving its name and a description separated by a tabor at least three spaces. (This index file is not generatedautomatically.) Note that a demo does not have a specified encoding andso should be anASCII file (seeEncoding issues). Functiondemo() will use the package encoding if there is one, but this ismainly useful for non-ASCII comments.

The contents of theinst subdirectory will be copied recursivelyto the installation directory. Subdirectories ofinst should notinterfere with those used by R (currently,R,data,demo,exec,libs,man,help,html andMeta, and earlier versions usedlatex,R-ex). The copying of theinst happens aftersrcis built so itsMakefile can create files to be installed. Toexclude files from being installed, one can specify a list of excludepatterns in file.Rinstignore in the top-level source directory.These patterns should be Perl-like regular expressions (see the help forregexp in R for the precise details), one per line, to bematched case-insensitively against the file and directory paths, e.g.doc/.*[.]png$ will exclude all PNG files ininst/doc basedon the extension.

Note that with the exceptions ofINDEX,LICENSE/LICENCE andNEWS, information files at thetop level of the package willnot be installed and so not beknown to users of Windows and macOS compiled packages (and not seenby those who useR CMD INSTALL orinstall.packages()on the tarball). So any information files you wish an end user to seeshould be included ininst. Note that if the named exceptionsalso occur ininst, the version ininst will be that seenin the installed package.

Things you might like to add toinst are aCITATION filefor use by thecitation function, and aNEWS.Rd file foruse by thenews function. See its help page for the specificformat restrictions of theNEWS.Rd file.

Another file sometimes needed ininst isAUTHORS orCOPYRIGHTS to specify the authors or copyright holders when thisis too complex to put in theDESCRIPTION file.

Subdirectorytests 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 (or.ras from R 3.4.0) file, orvia a.Rin file containingcode which in turn creates the corresponding.R file (e.g., bycollecting all function objects in the package and then calling themwith the strangest arguments). The results of running a.R fileare written to a.Rout file. If there is acorresponding25.Rout.save file, these two arecompared, with differences being reported but not causing an error. Thedirectorytests is copied to the check area, and the tests arerun with the copy as the working directory and withR_LIBS set toensure that the copy of the package installed during testing will befound bylibrary(pkg_name). Note that the package-specifictests are run in a vanilla R session without setting therandom-number seed, so tests which use random numbers will need to setthe seed to obtain reproducible results (and it can be helpful to do soin all cases, to avoid occasional failures when tests are run).

If directorytests has a subdirectoryExamples containinga filepkg-Ex.Rout.save, this is compared to the outputfile for running the examples when the latter are checked. Referenceoutput should be produced without having the--timings optionset (and note that--as-cran sets it).

If reference output is included for examples, demos, tests or vignettes do makesure that it is fully reproducible, as it will be compared verbatim tothat produced in a check run, unless the ‘IGNORE_RDIFF’ markup isused. Things which trip up maintainers include displayed versionnumbers from loading other packages, printing numerical results to anunreproducibly high precision and printing timings. Another trap issmall values which are in fact rounding error from zero: consider usingzapsmall.

Subdirectoryexec could contain additional executable scripts thepackage needs, typically scripts for interpreters such as the shell,Perl, or Tcl. NB: only files (and not directories) underexecare installed (and those with names starting with a dot are ignored),and they are all marked as executable (mode755, moderated by‘umask’) on POSIX platforms. Note too that this is not suitablefor executableprograms since some platforms support multiplearchitectures using the same installed package directory.

Subdirectorypo is used for files related tolocalization:seeInternationalization.

Subdirectorytools is the preferred place for auxiliary filesneeded during configuration, and also for sources need to re-createscripts (e.g. M4 files forautoconf: some prefer to putthose in a subdirectorym4 oftools).


Next:, Previous:, Up:Package structure   [Contents][Index]

1.1.6 Data in packages

Thedata subdirectory is for data files, either to be madeavailablevia lazy-loading or for loading usingdata().(The choice is made by the ‘LazyData’ field in theDESCRIPTION file: the default is not to do so.) It should not beused for other data files needed by the package, and the convention hasgrown up to use directoryinst/extdata for such files.

Data files can have one of three types as indicated by their extension:plain R code (.R or.r), tables (.tab,.txt, or.csv, see?data for the file formats, andnote that.csv isnot the standard26 CSV format), orsave() images (.RData or.rda). The files shouldnot be hidden (have names starting with a dot). Note that R codeshould be if possible “self-sufficient” and not make use of extrafunctionality provided by the package, so that the data file can also beused without having to load the package or its namespace: it should runas silently as possible and not change thesearch() path byattaching packages or other environments.

Images (extensions.RData27 or.rda) can containreferences to the namespaces of packages that were used to create them.Preferably there should be no such references in data files, and in anycase they should only be to packages listed in theDepends andImports fields, as otherwise it may be impossible to install thepackage. To check for such references, load all the images into avanilla R session, runstr() on all the datasets, and look atthe output ofloadedNamespaces().

Particular care is needed where a dataset or one of its components is ofan S4 class, especially if the class is defined in a different package.First, the package containing the class definition has to be availableto do useful things with the dataset, so that package must be listed inImports orDepends (even if this gives a check warningabout unused imports). Second, the definition of an S4 class canchange, and often is unnoticed when in a package with a differentauthor. So it may be wiser to use the.R form and use that tocreate the dataset object when needed (loading package namespaces butnot attaching them by usingrequireNamespace(pkg, quietly =TRUE) and usingpkg:: to refer to objects in thenamespace).

If you are not using ‘LazyData’ and either your data files are largeor e.g., you usedata/foo.R scripts to produce your data, loadingyour namespace, youcan speed up installation by providing a filedatalist in thedata subdirectory. This should have one line per topic thatdata() will find, in the format ‘foo’ ifdata(foo)provides ‘foo’, or ‘foo: bar bah’ ifdata(foo) provides‘bar’ and ‘bah’.R CMD build will automatically addadatalist file todata directories of over 1Mb, using thefunctiontools::add_datalist.

Tables (.tab,.txt, or.csv files) can becompressed bygzip,bzip2 orxz,optionally with additional extension.gz,.bz2 or.xz.

If your package is to be distributed, do consider the resourceimplications of large datasets for your users: they can make packagesvery slow to download and use up unwelcome amounts of storage space, aswell as taking many seconds to load. It is normally best to distributelarge datasets as.rda images prepared bysave(, compress =TRUE) (the default). Usingbzip2 orxz compressionwill usually reduce the size of both the package tarball and theinstalled package, in some cases by a factor of two or more.

Packagetools has a couple of functions to help with data images:checkRdaFiles reports on the way the image was saved, andresaveRdaFiles will re-save with a different type of compression,including choosing the best type for that particular image.

Many packages using ‘LazyData’ will benefit from using a form ofcompression other thangzip in the installed lazy-loadingdatabase. This can be selected by the--data-compress optiontoR CMD INSTALL or by using the ‘LazyDataCompression’field in theDESCRIPTION file. Useful values arebzip2,xz and the default,gzip: valuenone is alsoaccepted. The only way to discover which is best is to try them all andlook at the size of thepkgname/data/Rdata.rdb file. Afunction to do that (quoting sizes in KB) is

CheckLazyDataCompression <- function(pkg){    pkg_name <- sub("_.*", "", pkg)    lib <- tempfile(); dir.create(lib)    zs <- c("gzip", "bzip2", "xz")    res <- integer(3); names(res) <- zs    for (z in zs) {        opts <- c(paste0("--data-compress=", z),                  "--no-libs", "--no-help", "--no-demo", "--no-exec", "--no-test-load")        install.packages(pkg, lib, INSTALL_opts = opts, repos = NULL, quiet = TRUE)        res[z] <- file.size(file.path(lib, pkg_name, "data", "Rdata.rdb"))    }    ceiling(res/1024)}

(applied to a source package without any ‘LazyDataCompression’field).R CMD check will warn if it finds apkgname/data/Rdata.rdb file of more than 5MB without‘LazyDataCompression’ being set. If you see that, runCheckLazyDataCompression() and set the field – togzip inthe unlikely event28 that is the best choice.

The analogue forsysdata.rda is field ‘SysDataCompression’:the default isxz for files bigger than 1MB otherwisegzip.

Lazy-loading is not supported for very large datasets (those which whenserialized exceed 2GB, the limit for the format on 32-bit platforms).


Next:, Previous:, Up:Package structure   [Contents][Index]

1.1.7 Non-R scripts in packages

Code which needs to be compiled (C, C++, Fortran …)is included in thesrc subdirectory and discussed elsewhere inthis document.

Subdirectoryexec could be used for scripts for interpreters suchas the shell, BUGS, JavaScript, Matlab, Perl, PHP (amap),Python or Tcl (Simile), or even R. However, it seems morecommon to use theinst directory, for exampleWriteXLS/inst/Perl,NMF/inst/m-files,RnavGraph/inst/tcl,RProtoBuf/inst/python andemdbook/inst/BUGS andgridSVG/inst/js.

Java code is a special case: except for very small programs,.java files should be byte-compiled (to a.class file) anddistributed as part of a.jar file: the conventional location forthe.jar file(s) isinst/java. It is desirable (andrequired under an Open Source license) to make the Java source filesavailable: this is best done in a top-leveljava directory in thepackage—the source files should not be installed.

If your package requires one of these interpreters or an extension thenthis should be declared in the ‘SystemRequirements’ field of itsDESCRIPTION file. (Users of Java most often do soviarJava, when depending on/importing that suffices unless thereis a version requirement on Java code in the package.)

Windows and Mac users should be aware that the Tcl extensions‘BWidget’ and ‘Tktable’ (which have sometimes been included inthe Windows29 and macOS R installers)are extensions and do need to be declared (and that‘Tktable’ is less widely available than it used to be, includingnot in the main repositories for major Linux distributions).‘BWidget’ needs to be installed by the user on other OSes. This isfairly easy to do: first find the Tcl search path:

library(tcltk)strsplit(tclvalue('auto_path'), " ")[[1]]

then download the sources fromhttps://sourceforge.net/projects/tcllib/files/BWidget/and in a terminal run something like

tar xf bwidget-1.9.14.tar.gzsudo mv bwidget-1.9.14 /usr/local/lib

substituting a location on the Tcl search path for/usr/local/lib ifneeded. (If no location on that search path is writeable, you will needto add one each time ‘BWidget’ is to be used withtcltk::addTclPath().)

To (silently) test for the presence of ‘Tktable’ one can use

library(tcltk)have_tktable <- !isFALSE(suppressWarnings(tclRequire('Tktable')))

Installing ‘Tktable’ needs a C compiler and the Tk headers (notnecessarily installed with Tcl/Tk). At the time of writing the latestsources (from 2008) were available fromhttps://sourceforge.net/projects/tktable/files/tktable/2.10/Tktable2.10.tar.gz/download,but needed patching for current Tk (8.6.11, but not 8.6.10) – a patchcan be found athttps://www.stats.ox.ac.uk/pub/bdr/Tktable/. Fora system installation of Tk you may need to install ‘Tktable’ as‘root’ as on e.g. Fedora all the locations onauto_pathare owned by ‘root’.


Previous:, Up:Package structure   [Contents][Index]

1.1.8 Specifying URLs

URLs in many places in the package documentation will be converted toclickable hyperlinks in at least some of their renderings. So care isneeded that their forms are correct and portable.

The full URL should be given, including the scheme (often ‘http://’or ‘https://’) and a final ‘/’ for references to directories.

Spaces in URLs are not portable and how they are handled does vary byHTTP server and by client. There should be no space in the host part ofan ‘http://’ URL, and spaces in the remainder should be encoded,with each space replaced by ‘%20’.

Reserved characters should be encoded unless used in their reservedsense: see the help onURLencode().

The canonical URL for aCRAN package is

https://cran.r-project.org/package=pkgname

and not a version starting‘https://cran.r-project.org/web/packages/pkgname’.


Next:, Previous:, Up:Creating R packages   [Contents][Index]

1.2 Configure and cleanup

Note that most of this section is specific to Unix-alikes: see thecomments later on about the Windows port of R.

If your package needs some system-dependent configuration beforeinstallation you can include an executable (Bourne30 shell scriptconfigurein your package which (if present) is executed byR CMD INSTALLbefore any other action is performed. This can be a script created bythe Autoconf mechanism, but may also be a script written by yourself.Use this to detect if any nonstandard libraries are present such thatcorresponding code in the package can be disabled at install time ratherthan giving error messages when the package is compiled or used. Tosummarize, the full power of Autoconf is available for your extensionpackage (including variable substitution, searching for libraries,etc.). Background and useful tips on Autoconf and related tools(includingpkg-config described below) can be found athttps://autotools.info/.

Aconfigure script is run in an environment which has all theenvironment variables set for an R session (seeR_HOME/etc/Renviron) plusR_PACKAGE_NAME (the name ofthe package),R_PACKAGE_DIR (the path of the target installationdirectory of the package, a temporary location for staged installs) andR_ARCH (the arch-dependent part of the path, often empty).

Under a Unix-alike only, an executable (Bourne shell) scriptcleanup is executed as the last thing byR CMD INSTALL ifoption--clean was given, and byR CMD build whenpreparing the package for building from its source.

As an example consider we want to use functionality provided by a (C orFortran) libraryfoo. Using Autoconf, we can create a configurescript which checks for the library, sets variableHAVE_FOO toTRUE if it was found and toFALSE otherwise, and thensubstitutes this value into output files (by replacing instances of‘@HAVE_FOO@’ in input files with the value ofHAVE_FOO).For example, if a function namedbar is to be made available bylinking against libraryfoo (i.e., using-lfoo), onecould use

AC_CHECK_LIB(foo,fun, [HAVE_FOO=TRUE], [HAVE_FOO=FALSE])AC_SUBST(HAVE_FOO)......AC_CONFIG_FILES([foo.R])AC_OUTPUT

inconfigure.ac (assuming Autoconf 2.50 or later).

The definition of the respective R function infoo.R.in could be

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

From this fileconfigure creates the actual R source filefoo.R looking like

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

if libraryfoo 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 missingfunctionality, respectively.

You will very likely need to ensure that the same C compiler andcompiler flags are used in theconfigure tests as when compilingR or your package. Under a Unix-alike, you can achieve this byincluding the following fragment early inconfigure.ac(before callingAC_PROG_CC or anything which calls it)

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

(Using ‘${R_HOME}/bin/R’ rather than just ‘R’ is necessaryin order to use the correct version of R when running the script aspart ofR CMD INSTALL, and the quotes since ‘${R_HOME}’might contain spaces.)

If your code does load checks (for example, to check for an entry point ina library or to run code) then you will also need

LDFLAGS=`"${R_HOME}/bin/R" CMD config LDFLAGS`

Packages written with C++ need to pick up the details for the C++compiler and switch the current language to C++ by something like

CXX=`"${R_HOME}/bin/R" CMD config CXX`if test -z "$CXX"; then  AC_MSG_ERROR([No C++ compiler is available])fiCXXFLAGS=`"${R_HOME}/bin/R" CMD config CXXFLAGS`CPPFLAGS=`"${R_HOME}/bin/R" CMD config CPPFLAGS`AC_LANG(C++)

The latter is important, as for example C headers may not be availableto C++ programs or may not be written to avoid C++ name-mangling. Notethat an R installation is not required to have a C++ compiler so‘CXX’ may be empty. If the package specifies a non-default C++standard, use theconfig variable names (such asCXX17)appropriate to the standard, but still setCXX andCXXFLAGS.

You can useR CMD config to get the value of the basicconfiguration variables, and also the header and library flags necessaryfor linking a front-end executable program against R, seeR CMDconfig --help for details. If you do, it is essential that you useboth the command and the appropriate flags, so that for example‘CC’ must always be used with ‘CFLAGS’ and (for code to belinked into a shared library) ‘CPICFLAGS’. For Fortran, be carefulto use ‘FC FFLAGS FPICFLAGS’ for fixed-form Fortran and‘FC FCFLAGS FPICFLAGS’ for free-form Fortran.

As from R 4.3.0, variables

CC CFLAGS CXX CXXFLAGS CPPFLAGS LDFLAGS FC FCFLAGS

are set in the environment (if not already set) whenconfigureis called fromR CMD INSTALL, in case the script forgets toset them as described above. This includes making use of the selected Cstandard (but not the C++ standard as that is selected at a later stagebyR CMD SHLIB).

To check for an external BLAS library using theAX_BLAS macrofrom the official Autoconf MacroArchive31, onecan use

FC=`"${R_HOME}/bin/R" CMD config FC`FCLAGS=`"${R_HOME}/bin/R" CMD config FFLAGS`AC_PROG_FCFLIBS=`"${R_HOME}/bin/R" CMD config FLIBS`AX_BLAS([], AC_MSG_ERROR([could not find your BLAS library], 1))

Note thatFLIBS as determined by R must be used to ensure thatFortran code works on all R platforms.

N.B.: If theconfigure script creates files, e.g.src/Makevars, you do need acleanup script to removethem. OtherwiseR CMD build may ship the files that arecreated. For example, packageRODBC has

#!/bin/shrm -f config.* src/Makevars src/config.h

As this example shows,configure often creates working filessuch asconfig.log. If you use a hand-crafted scriptrather than one created byautoconf, it is highly recommendedthat you log its actions to fileconfig.log.

If your configure script needs auxiliary files, it is recommended thatyou ship them in atools directory (as R itself does).

You should bear in mind that the configure script will not be used onWindows systems. If your package is to be made publicly available,please give enough information for a user on a non-Unix-alike platformto configure it manually, or provide aconfigure.win script (orconfigure.ucrt) to be used on that platform. (Optionally, therecan be acleanup.win script (orcleanup.ucrt). Bothshould be shell scripts to be executed byash, which is aminimal version of Bourne-stylesh. As from R 4.2.0,bash is used. Whenconfigure.win (orconfigure.ucrt) is run the environment variablesR_HOME(which uses ‘/’ as the file separator),R_ARCH andR_ARCH_BIN will be set. UseR_ARCH to decide if this is a64-bit build for Intel (its value there is ‘/x64’) and to install DLLs to thecorrect place (${R_HOME}/libs${R_ARCH}). UseR_ARCH_BIN to find the correct place under thebindirectory, e.g.${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe. Ifaconfigure.win script does compilation (including callingR CMD SHLIB), most of the considerations above apply.

As the scripts on Windows are executed assh ./configure.winand similar, any ’shebang’ first line (such as#! /bin/bash) istreated as a comment.

In some rare circumstances, the configuration and cleanup scripts needto know the location into which the package is being installed. Anexample of this is a package that uses C code and creates two sharedobject/DLLs. Usually, the object that is dynamically loaded by Ris linked against the second, dependent, object. On some systems, wecan add the location of this dependent object to the object that isdynamically loaded by R. This means that each user does not have toset the value of theLD_LIBRARY_PATH (or equivalent) environmentvariable, but that the secondary object is automatically resolved.Another example is when a package installs support files that arerequired at run time, and their location is substituted into an Rdata structure at installation time.The names of the top-level library directory (i.e., specifiablevia the ‘-l’ argument) and the directory of the packageitself are made available to the installation scriptsvia the twoshell/environment variablesR_LIBRARY_DIR andR_PACKAGE_DIR.Additionally, the name of the package (e.g. ‘survival’ or‘MASS’) being installed is available from the environment variableR_PACKAGE_NAME. (Currently the value ofR_PACKAGE_DIR isalways${R_LIBRARY_DIR}/${R_PACKAGE_NAME}, but this used not tobe the case when versioned installs were allowed. Its main use is inconfigure.win (orconfigure.ucrt) scripts for the installation path of externalsoftware’s DLLs.) Note that the value ofR_PACKAGE_DIR maycontain spaces and other shell-unfriendly characters, and so should bequoted in makefiles and configure scripts.

One of the more tricky tasks can be to find the headers and libraries ofexternal software. One tool which is increasingly available onUnix-alikes (but not by default32 on macOS) todo this ispkg-config. Theconfigure script will needto test for the presence of the command itself33(see for example packagetiff), and if present it can beasked if the software is installed, of a suitable version and forcompilation/linking flags by e.g.

$ pkg-config --exists 'libtiff-4 >= 4.1.0' --print-errors # check the status$ pkg-config --modversion libtiff-44.3.0$ pkg-config --cflags libtiff-4-I/usr/local/include$ pkg-config --libs libtiff-4-L/usr/local/lib -ltiff$ pkg-config --static --libs libtiff-4-L/usr/local/lib -ltiff -lwebp -llzma -ljpeg -lz

Note thatpkg-config --libs gives the information required tolink against the default version34 of that library (usually the dynamic one), andpkg-config --static --libs may be needed if the static library isto be used.

Static libraries are commonly used on macOS and Windows to facilitatebundling external software with binary distributions of packages. Thismeans that portable (source) packages need to allow for this. It isnot safe to just usepkg-config --static --libs, asthat will often include further libraries that are not necessarilyinstalled on the user’s system (or maybe only the versioned library suchaslibjbig.so.2.1 is installed and notlibjbig.so whichwould be needed to use-ljbig sometimes included inpkg-config --static --libs libtiff-4).

Another issue is thatpkg-config --exists may not be reliable.It checks not only that the ‘module’ is available butall of thedependencies, including those in principle needed for static linking.(XQuartz 2.8.x only distributed dynamic libraries and not some of the.pc files needed for--exists.)

Sometimes the name by which the software is known topkg-config is not what one might expect (e.g.‘libxml-2.0’ even for 2.9.x). To get a complete list use

pkg-config --list-all | sort

Some external software provides a-config command to do a similarjob topkg-config, including

curl-config   freetype-config  gdal-config    geos-configgsl-config    iodbc-config     libpng-config  nc-configpcre-config   pcre2-config     xml2-config    xslt-config

(curl-config is forlibcurl notcurl.nc-config is fornetcdf.) Most have an option to usestatic libraries.

N.B. These commands indicate what header paths andlibraries are needed, but they do not obviate the need to check that therecipes they give actually work. (This is especially necessary forplatforms which use static linking.)

If using Autoconf it is good practice to include all the Autoconfsources in the package (and required for an Open Source package andtested byR CMD check --as-cran). This will include the fileconfigure.ac35 in the top-level directory of the package. Ifextensions written inm4 are needed, these should be includedunder the directorytools and included fromconfigure.acvia e.g.,

m4_include([tools/ax_pthread.m4])

Alternatively, Autoconf can be asked to search all.m4 files in adirectory by including something like36

AC_CONFIG_MACRO_DIR([tools/m4])

One source of such extensions is the ‘Autoconf Archive’(https://www.gnu.org/software/autoconf-archive/. It is notsafe to assume this is installed on users’ machines, so the extensionshould be shipped with the package (taking care to comply with itslicence).


Next:, Up:Configure and cleanup   [Contents][Index]

1.2.1 UsingMakevars

Sometimes writing your ownconfigure script can be avoided bysupplying a fileMakevars: also one of the most common uses of aconfigure script is to makeMakevars fromMakevars.in.

AMakevars file is a makefile and is used as one of severalmakefiles byR CMD SHLIB (which is called byR CMDINSTALL to compile code in thesrc directory). It should bewritten if at all possible in a portable style, in particular (exceptforMakevars.win andMakevars.ucrt) without the use of GNUextensions.

The most common use of aMakevars file is to set additionalpreprocessor options (for example include paths and definitions) forC/C++ filesviaPKG_CPPFLAGS, and additional compilerflags by settingPKG_CFLAGS,PKG_CXXFLAGS orPKG_FFLAGS, for C, C++ or Fortran respectively (seeCreating shared objects).

N.B.: Include paths are preprocessor options, not compileroptions, andmust be set inPKG_CPPFLAGS as otherwiseplatform-specific paths (e.g. ‘-I/usr/local/include’) will takeprecedence.PKG_CPPFLAGS should contain ‘-I’, ‘-D’,‘-U’ and (where supported) ‘-include’ and ‘-pthread’options: everything else should be a compiler flag. The order of flagsmatters, and using ‘-I’ inPKG_CFLAGS orPKG_CXXFLAGShas led to hard-to-debug platform-specific errors.

Makevars can also be used to set flags for the linker, forexample ‘-L’ and ‘-l’ options,viaPKG_LIBS.

When writing aMakevars file for a package you intend todistribute, take care to ensure that it is not specific to yourcompiler: flags such as-O2 -Wall -pedantic (and all other-W flags: for the Oracle compilers these were used to passarguments to compiler phases) are all specific to GCC (and compilers suchasclang which aim to be options-compatible with it).

Also, do not set variables such asCPPFLAGS,CFLAGS etc.:these should be settable by users (sites) through appropriate personal(site-wide)Makevars files.SeeCustomizing package compilation inR Installation and Administrationfor more information.

There are some macros37 which are set whilst configuring thebuilding of R itself and are stored inR_HOME/etcR_ARCH/Makeconf. That makefile is includedas aMakefileafterMakevars[.win], and the macrosit defines can be used in macro assignments and make command lines inthe latter. These include

FLIBS

A macro containing the set of libraries need to link Fortran code. Thismay need to be included inPKG_LIBS: it will normally be includedautomatically if the package contains Fortran source files in thesrc directory.

BLAS_LIBS

A macro containing the BLAS libraries used when building R. This mayneed to be included inPKG_LIBS. Beware that if it is empty thenthe R executable will contain all the double-precision anddouble-complex BLAS routines, but no single-precision nor complexroutines. IfBLAS_LIBS is included, thenFLIBS also needsto be38 included following it, as most BLASlibraries are written at least partially in Fortran. However, it canbe omitted if the package contains Fortran source code as that will addFLIBS to the link line.

LAPACK_LIBS

A macro containing the LAPACK libraries (and paths where appropriate)used when building R. This may need to be included inPKG_LIBS. It may point to a dynamic librarylibRlapackwhich contains the main double-precision LAPACK routines as well asthose double-complex LAPACK routines needed to build R, or it maypoint to an external LAPACK library, or may be empty if an external BLASlibrary also contains LAPACK.

[libRlapack includes all the double-precision LAPACK routineswhich were current in 2003 and a few more recent ones: a list of whichroutines are included is in filesrc/modules/lapack/README. Notethat an external LAPACK/BLAS library need not do so, as some were‘deprecated’ (and not compiled by default) in LAPACK 3.6.0 in late2015.]

For portability, the macrosBLAS_LIBS andFLIBS shouldalways be includedafterLAPACK_LIBS (and in that order).

SAFE_FFLAGS

A macro containing flags which are needed to circumventover-optimization of FORTRAN code: it is might be ‘-g -O2-ffloat-store’ or ‘-g -O2 -msse2 -mfpmath=sse’ on ‘ix86’platforms usinggfortran. Note that this isnot anadditional flag to be used as part ofPKG_FFLAGS, but areplacement forFFLAGS. See the example later in this section.

Setting certain macros inMakevars will preventR CMDSHLIB setting them: in particular ifMakevars sets‘OBJECTS’ it will not be set on themake command line.This can be useful in conjunction with implicit rules to allow othertypes of source code to be compiled and included in the shared object.It can also be used to control the set of files which are compiled,either by excluding some files insrc or including some files insubdirectories. For example

OBJECTS = 4dfp/endianio.o 4dfp/Getifh.o R4dfp-object.o

Note thatMakevars should not normally contain targets, as it isincluded before the default makefile andmake will call thefirst target, intended to beall in the default makefile. If youreally need to circumvent that, use a suitable (phony) targetallbefore any actual targets inMakevars.[win]: for example packagefastICA used to have

PKG_LIBS = @BLAS_LIBS@SLAMC_FFLAGS=$(R_XTRA_FFLAGS) $(FPICFLAGS) $(SHLIB_FFLAGS) $(SAFE_FFLAGS)all: $(SHLIB)slamc.o: slamc.f        $(FC) $(SLAMC_FFLAGS) -c -o slamc.o slamc.f

needed to ensure that the LAPACK routines find some constants withoutinfinite looping. The Windows equivalent was

all: $(SHLIB)slamc.o: slamc.f        $(FC) $(SAFE_FFLAGS) -c -o slamc.o slamc.f

(since the other macros are all empty on that platform, and R’sinternal BLAS was not used). Note that the first target inMakevars will be called, but for back-compatibility it is bestnamedall.

If you want to create and then link to a library, say using code in asubdirectory, use something like

.PHONY: all mylibsall: $(SHLIB)$(SHLIB): mylibsmylibs:        (cd subdir; $(MAKE))

Be careful to create all the necessary dependencies, as there is noguarantee that the dependencies ofall will be run in aparticular order (and some of theCRAN build machines usemultiple CPUs and parallel makes). In particular,

all: mylibs

doesnot suffice. GNU make does allow the construct

.NOTPARALLEL: allall: mylibs $(SHLIB)

but that is not portable.dmake andpmake allow thesimilar.NO_PARALLEL, also not portable: some variants ofpmake accept.NOTPARALLEL as an alias for.NO_PARALLEL.

Note that on Windows it is required thatMakevars[.win, .ucrt] doescreate a DLL: this is needed as it is the only reliable way to ensurethat building a DLL succeeded. If you want to use thesrcdirectory for some purpose other than building a DLL, use aMakefile.win orMakefile.ucrt file.

It is sometimes useful to have a target ‘clean’ inMakevars,Makevars.win orMakevars.ucrt:this will be used byR CMD build toclean up (a copy of) the package sources. When it is run bybuild it will have fewer macros set, in particular not$(SHLIB), nor$(OBJECTS) unless set in the file itself.It would also be possible to add tasks to the target ‘shlib-clean’which is run byR CMD INSTALL andR CMD SHLIB withoptions--clean and--preclean.

Avoid the use of default (also known as ‘implicit’ rules) in makefiles,as these aremake-specific. Even when mandated by POSIX –GNUmake does not comply and this has broken packageinstallation.

An unfortunately common error is to have

all: $(SHLIB) clean

which asksmake to clean in parallel with compiling the code.Not only does this lead to hard-to-debug installation errors, it wipesout all the evidence of any error (from a parallel make or not). It ismuch better to leave cleaning to the end user using the facilities inthe previous paragraph.

If you want to run R code inMakevars, e.g. to findconfiguration information, please do ensure that you use the correctcopy ofR orRscript: there might not be one in the pathat all, or it might be the wrong version or architecture. The correctway to do this isvia

"$(R_HOME)/bin$(R_ARCH_BIN)/Rscript"filename"$(R_HOME)/bin$(R_ARCH_BIN)/Rscript" -e 'R expression'

where$(R_ARCH_BIN) is only needed currently on Windows.

Environment or make variables can be used to select different macros forIntel 64-bit code or code for other architectures, for example(GNUmake syntax, allowed on Windows)

ifeq "$(WIN)" "64"PKG_LIBS =value for 64-bit Intel WindowselsePKG_LIBS =value for unknown Windows architecturesendif

On Windows there is normally a choice between linking to an importlibrary or directly to a DLL. Where possible, the latter is much morereliable: import libraries are tied to a specific toolchain, and inparticular on 64-bit Windows two different conventions have beencommonly used. So for example instead of

PKG_LIBS = -L$(XML_DIR)/lib -lxml2

one can use

PKG_LIBS = -L$(XML_DIR)/bin -lxml2

since on Windows-lxxx will look in turn for

libxxx.dll.axxx.dll.alibxxx.axxx.liblibxxx.dllxxx.dll

where the first and second are conventionally import libraries, thethird and fourth often static libraries (with.lib intended forVisual C++), but might be import libraries. See for examplehttps://sourceware.org/binutils/docs-2.20/ld/WIN32.html#WIN32.

The fly in the ointment is that the DLL might not be namedlibxxx.dll, and in fact on 32-bit Windows there was alibxml2.dll whereas on one build for 64-bit Windows the DLL iscalledlibxml2-2.dll. Using import libraries can cover overthese differences but can cause equal difficulties.

If static libraries are available they can save a lot of problems withrun-time finding of DLLs, especially when binary packages are to bedistributed and even more when these support both architectures. Whereusing DLLs is unavoidable we normally arrange (viaconfigure.win orconfigure.ucrt) to ship them in the same directory as the packageDLL.


1.2.1.1OpenMP support

There is some support for packages which wish to useOpenMP39. Themake macros

SHLIB_OPENMP_CFLAGSSHLIB_OPENMP_CXXFLAGSSHLIB_OPENMP_FFLAGS

are available for use insrc/Makevars,src/Makevars.win orMakevars.ucrt. Include the appropriate macro inPKG_CFLAGS,PKG_CXXFLAGS and so on, and also inPKG_LIBS (but see below for Fortran). C/C++ code that needs tobe conditioned on the use ofOpenMP can be used inside#ifdef_OPENMP: note that some toolchains used for R (including Apple’s formacOS40 and some others usingclang41) have noOpenMP support at all, not evenomp.h.

For example, a package with C code written forOpenMP should have insrc/Makevars the lines

Note that the macroSHLIB_OPENMP_CXXFLAGS applies to the defaultC++ compiler and not necessarily to the C++17/20/23/26 compiler: users of thelatter should do their ownconfigure checks. If you do useyour own checks, make sure thatOpenMP support is complete by compilingand linking anOpenMP-using program: on some platforms the runtimelibrary is optional and on others that library depends on other optionallibraries.

Some care is needed when compilers are from different families which mayuse differentOpenMP runtimes (e.g.clangvs GCCincludinggfortran, although it is often possible to use theclang runtime with GCC but notvice versa: howevergfortran >= 9 may generate calls not in theclangruntime). For a package with Fortran code usingOpenMP the appropriatelines are

as the C compiler will be used to link the package code. There areplatforms on which this does not workfor someOpenMP-using codeand installation will fail. Since R >= 3.6.2 the best alternativefor a package with only Fortran sources usingOpenMP is to use

insrc/Makevars,src/Makevars.win orMakevars.ucrt.Note however, thatwhen this is used$(FLIBS) should not be included inPKG_LIBS since it is for linking Fortran-compiled code by the Ccompiler.

Common platforms may inline allOpenMP calls and so tolerate theomission of theOpenMP flag fromPKG_LIBS, but this usuallyresults in an installation failure with a different compiler orcompilation flags. So cross-check that e.g.-fopenmp appearsin the linking line in the installation logs.

It is not portable to useOpenMP with more than one of C, C++ andFortran in a single package since it is not uncommon that the compilersare of different families.

For portability, any C/C++ code using theomp_* functions shouldinclude theomp.h header: some compilers (but not all) include itwhenOpenMP mode is switched on (e.g.via flag-fopenmp).

There is nothing42 to say whatversion ofOpenMP is supported: version 4.0 (and much of 4.5 or 5.0) issupported by recent versions of the Linux and Windows platforms, butportable packages cannot assume that end users have recent versions.Appleclang on macOS has noOpenMP support.https://www.openmp.org/resources/openmp-compilers-tools/ givessome idea of what compilers support what versions. Note that supportfor Fortran compilers is often less up-to-date and that page suggests itis unwise to rely on a version later than 3.1. Which introduced aFortranOpenMP module, so Fortran users ofOpenMP should include

Rarely, usingOpenMP withclang on Linux generates calls inlibatomic, resulting in loading messages like

The workaround is to link with-latomic (having checked it exists).

The performance ofOpenMP varies substantially between platforms. TheWindows implementation has substantial overheads, so is only beneficialif quite substantial tasks are run in parallel. Also, on Windows newthreads are started with the default43FPU control word, so computations done onOpenMPthreads will not make use of extended-precision arithmetic which is thedefault for the main process.

Do not include these macros unless your code does make use ofOpenMP(possibly for C++ via included external headers): this can result in theOpenMP runtime being linked in, threads being started, ….

Calling any of the R API from threaded code is ‘for experts only’ andstrongly discouraged. Many functions in the R API modify internalR data structures and might corrupt these data structures if calledsimultaneously from multiple threads. Most R API functions cansignal errors, which must only happen on the R main thread. Also,external libraries (e.g. LAPACK) may not be thread-safe.

Packages are not standard-alone programs, and an R process couldcontain more than oneOpenMP-enabled package as well as other components(for example, an optimized BLAS) making use ofOpenMP. So carefulconsideration needs to be given to resource usage.OpenMP works withparallel regions, and for most implementations the default is to use asmany threads as ‘CPUs’ for such regions. Parallel regions can benested, although it is common to use only a single thread below thefirst level. The correctness of the detected number of ‘CPUs’ and theassumption that the R process is entitled to use them all are bothdubious assumptions. One way to limit resources is to limit the overallnumber of threads available toOpenMP in the R process: this can bedonevia environment variableOMP_THREAD_LIMIT, whereimplemented.44 Alternatively, the number of threads perregion can be limited by the environment variableOMP_NUM_THREADSor API callomp_set_num_threads, or, better, for the regions inyour code as part of their specification. E.g. R uses45

#pragma omp parallel for num_threads(nthreads) ...

That way you only control your own code and not that of otherOpenMP users.

Note that setting environment variables to controlOpenMP isimplementation-dependent and may need to be done outside the Rprocess or before any use ofOpenMP (which might be by another processor R itself). Also, implementation-specific variables such asKMP_THREAD_LIMIT might take precedence.


1.2.1.2 Using pthreads

There is no direct support for the POSIX threads (more commonly known aspthreads): by the time we considered adding it several packageswere using it unconditionally so it seems that nowadays it isuniversally available on POSIX operating systems.

For reasonably recent versions ofgcc andclang thecorrect specification is

PKG_CPPFLAGS = -pthreadPKG_LIBS = -pthread

(and the plural version is also accepted on some systems/versions). Forother platforms the specification is

PKG_CPPFLAGS = -D_REENTRANTPKG_LIBS = -lpthread

(and note that the library name is singular). This is what-pthread does on all known current platforms (although earlierversions of OpenBSD used a different library name).

For a tutorial seehttps://hpc-tutorials.llnl.gov/posix/.

POSIX threads are not normally used on Windows which has its own nativeconcepts of threads: however, recent toolchains do provide thepthreads header and library.

The presence of a workingpthreads implementation cannot beunambiguously determined without testing for yourself: however, that‘_REENTRANT’ is defined in C/C++ code is a good indication.

Note that not allpthreads implementations are equivalent as partsare optional (seehttps://pubs.opengroup.org/onlinepubs/009695399/basedefs/pthread.h.html):for example, macOS lacks the ‘Barriers’ option.

See also the comments on thread-safety and performance underOpenMP: onall known R platformsOpenMP is implementedviapthreads and the known performance issues are in the latter.


1.2.1.3 Compiling in sub-directories

Package authors fairly often want to organize code in sub-directories ofsrc, for example if they are including a separate piece ofexternal software to which this is an R interface.

One simple way is simply to setOBJECTS to be all the objectsthat need to be compiled, including in sub-directories. For example,CRAN packageRSiena has

SOURCES = $(wildcard data/*.cpp network/*.cpp utils/*.cpp model/*.cpp model/*/*.cpp model/*/*/*.cpp)OBJECTS = siena07utilities.o siena07internals.o siena07setup.o siena07models.o $(SOURCES:.cpp=.o)

One problem with that approach is that unless GNU make extensions areused, the source files need to be listed and kept up-to-date. As in thefollowing fromCRAN packagelossDev:

OBJECTS.samplers = samplers/ExpandableArray.o samplers/Knots.o \  samplers/RJumpSpline.o samplers/RJumpSplineFactory.o \  samplers/RealSlicerOV.o samplers/SliceFactoryOV.o samplers/MNorm.oOBJECTS.distributions = distributions/DSpline.o \  distributions/DChisqrOV.o distributions/DTOV.o \  distributions/DNormOV.o distributions/DUnifOV.o distributions/RScalarDist.oOBJECTS.root = RJump.oOBJECTS = $(OBJECTS.samplers) $(OBJECTS.distributions) $(OBJECTS.root)

Where the subdirectory is self-contained code with a suitable makefile,the best approach is something like

PKG_LIBS = -LCsdp/lib -lsdp $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS)$(SHLIB): Csdp/lib/libsdp.aCsdp/lib/libsdp.a:        @(cd Csdp/lib && $(MAKE) libsdp.a \          CC="$(CC)" CFLAGS="$(CFLAGS) $(CPICFLAGS)" AR="$(AR)" RANLIB="$(RANLIB)")

Note the quotes: the macros can contain spaces, e.g.CC = "gcc-m64 -std=gnu99". Several authors have forgotten about parallel makes:the static library in the subdirectory must be made before the sharedobject ($(SHLIB)) and so the latter must depend on the former.Others forget the need46 forposition-independent code.

We really do not recommend usingsrc/Makefile instead ofsrc/Makevars, and as the example above shows, it is notnecessary.


Next:, Previous:, Up:Configure and cleanup   [Contents][Index]

1.2.2 Configure example

It may be helpful to give an extended example of using aconfigure script to create asrc/Makevars file: this isbased on that in theRODBC package.

Theconfigure.ac file follows:configure is created fromthis by runningautoconf in the top-level package directory(containingconfigure.ac).

AC_INIT([RODBC], 1.1.8) dnl package name, versiondnl A user-specifiable optionodbc_mgr=""AC_ARG_WITH([odbc-manager],            AC_HELP_STRING([--with-odbc-manager=MGR],                           [specify the ODBC manager, e.g. odbc or iodbc]),            [odbc_mgr=$withval])if test "$odbc_mgr" = "odbc" ; then  AC_PATH_PROGS(ODBC_CONFIG, odbc_config)fidnl Select an optional include path, from a configure optiondnl or from an environment variable.AC_ARG_WITH([odbc-include],            AC_HELP_STRING([--with-odbc-include=INCLUDE_PATH],                           [the location of ODBC header files]),            [odbc_include_path=$withval])RODBC_CPPFLAGS="-I."if test [ -n "$odbc_include_path" ] ; then   RODBC_CPPFLAGS="-I. -I${odbc_include_path}"else  if test [ -n "${ODBC_INCLUDE}" ] ; then     RODBC_CPPFLAGS="-I. -I${ODBC_INCLUDE}"  fifidnl ditto for a library pathAC_ARG_WITH([odbc-lib],            AC_HELP_STRING([--with-odbc-lib=LIB_PATH],                           [the location of ODBC libraries]),            [odbc_lib_path=$withval])if test [ -n "$odbc_lib_path" ] ; then   LIBS="-L$odbc_lib_path ${LIBS}"else  if test [ -n "${ODBC_LIBS}" ] ; then     LIBS="-L${ODBC_LIBS} ${LIBS}"  else    if test -n "${ODBC_CONFIG}"; then      odbc_lib_path=`odbc_config --libs | sed s/-lodbc//`      LIBS="${odbc_lib_path} ${LIBS}"    fi  fifidnl Now find the compiler and compiler flags to use: ${R_HOME=`R RHOME`}if test -z "${R_HOME}"; then  echo "could not determine R_HOME"  exit 1fiCC=`"${R_HOME}/bin/R" CMD config CC`CFLAGS=`"${R_HOME}/bin/R" CMD config CFLAGS`CPPFLAGS=`"${R_HOME}/bin/R" CMD config CPPFLAGS`if test -n "${ODBC_CONFIG}"; then  RODBC_CPPFLAGS=`odbc_config --cflags`fiCPPFLAGS="${CPPFLAGS} ${RODBC_CPPFLAGS}"dnl Check the headers can be foundAC_CHECK_HEADERS(sql.h sqlext.h)if test "${ac_cv_header_sql_h}" = no ||   test "${ac_cv_header_sqlext_h}" = no; then   AC_MSG_ERROR("ODBC headers sql.h and sqlext.h not found")fidnl search for a library containing an ODBC functionif test [ -n "${odbc_mgr}" ] ; then  AC_SEARCH_LIBS(SQLTables, ${odbc_mgr}, ,      AC_MSG_ERROR("ODBC driver manager ${odbc_mgr} not found"))else  AC_SEARCH_LIBS(SQLTables, odbc odbc32 iodbc, ,      AC_MSG_ERROR("no ODBC driver manager found"))fidnl for 64-bit ODBC need SQL[U]LEN, and it is unclear where they are defined.AC_CHECK_TYPES([SQLLEN, SQLULEN], , , [# include <sql.h>])dnl for unixODBC headerAC_CHECK_SIZEOF(long, 4)dnl substitute RODBC_CPPFLAGS and LIBSAC_SUBST(RODBC_CPPFLAGS)AC_SUBST(LIBS)AC_CONFIG_HEADERS([src/config.h])dnl and do substitution in the src/Makevars.in and src/config.hAC_CONFIG_FILES([src/Makevars])AC_OUTPUT

wheresrc/Makevars.in would be simply

PKG_CPPFLAGS = @RODBC_CPPFLAGS@PKG_LIBS = @LIBS@

A user can then be advised to specify the location of theODBCdriver manager files by options like (lines broken for easier reading)

R CMD INSTALL \  --configure-args='--with-odbc-include=/opt/local/include \  --with-odbc-lib=/opt/local/lib --with-odbc-manager=iodbc' \  RODBC

or by setting the environment variablesODBC_INCLUDE andODBC_LIBS.


Next:, Previous:, Up:Configure and cleanup   [Contents][Index]

1.2.3 Using modern Fortran code

R assumes that source files with extension.f are fixed-formFortran 90 (which includes Fortran 77), and passes them to the compilerspecified by macro ‘FC’. The Fortran compiler will also acceptfree-form Fortran 90/95 code with extension.f90 or(most47).f95.

The same compiler is used for both fixed-form and free-form Fortran code(with different file extensions and possibly different flags). MacroPKG_FFLAGS can be used for package-specific flags: for theun-encountered case that both are included in a single package and thatdifferent flags are needed for the two forms, macroPKG_FCFLAGSis also available for free-form Fortran.

The code used to build R allows a ‘Fortran 90’ compiler to beselected as ‘FC’, so platforms might be encountered which onlysupport Fortran 90. However, Fortran 95 is supported on all knownplatforms.

Most compilers specified by ‘FC’ will accept most Fortran 2003,2008 or 2018 code: such code should still use file extension.f90. Most current platforms usegfortran where youmight need to include-std=f2003,-std=f2008 or (fromversion 8)-std=f2018 inPKG_FFLAGS orPKG_FCFLAGS: the default is ‘GNU Fortran’, currently Fortran 2018(but Fortran 95 prior togfortran 8) with non-standardextensions. The other compilers in current use (LLVM’sflang (calledflang-new before version 20) and Intel’sifx) default to Fortran 201848.

It is good practice to describe a Fortran version requirement inDESCRIPTION’s ‘SystemRequirements’ field. Note that this ispurely for information: the package also needs aconfigurescript to determine the compiler and set appropriate option(s) and testthat the features needed from the standard are actually supported.

The Fortran 2023 released in Nov 2023: as usual compiler vendors areintroducing support incrementally.For Intel’sifx seehttps://www.intel.com/content/www/us/en/developer/articles/technical/fortran-language-and-openmp-features-in-ifx.html#Fortran%20Standards.For LLVM’sflang seehttps://flang.llvm.org/docs/F202X.html.gfortran does not have complete support even for the 2008 and2018 standards, but the option-std=f2023 is supported fromversion 14.1.

Modern versions of Fortran support modules, whereby compiling one sourcefile creates a module file which is then included in others. (Modulefiles typically have a.mod extension: they do depend on thecompiler used and so should never be included in a package.) Thiscreates a dependence whichmake will not know about and oftencauses installation with a parallel make to fail. Thus it is necessaryto add explicit dependencies tosrc/Makevars to tellmake the constraints on the order of compilation. Forexample, if fileiface.f90 creates a module ‘iface’ used byfilescmi.f90 anddmi.f90 thensrc/Makevars needsto contain something like

cmi.o dmi.o: iface.o

Some maintainers have found it difficult to findall the moduledependencies which leads to hard-to-reproduce installation failures.There are tools available to find these, including the Intel compiler’sflag-gen-dep andmakedepf90.

Note that it is not portable (although some platforms do accept it) todefine a module of the same name in multiple source files.


Next:, Previous:, Up:Configure and cleanup   [Contents][Index]

1.2.4 Using C++ code

R can be built without a C++ compiler although one is available (butnot necessarily installed) on all known R platforms. As from R4.0.0 a C++ compiler will be selected only if it conforms to the 2011standard (‘C++11’). A minor update49 (‘C++14’) was published inDecember 2014 and was used by default as from R 4.1.0 if supported.Further revisions ‘C++17’ (in December 2017), ‘C++20’ (with many newfeatures in December 2020) and ‘C++23’ (in October 2024) have beenpublished since. The next revision, ‘C++26’, is expected in 2026/7 andseveral compilers already have considerable support for the currentdraft.

The support in R for these standards has varied over the years: thisversion of the manual only describes R 4.3.0 and later. For detailsof earlier versions, see the corresponding section in their manuals.

The default standard for compiling R packages was changed to C++17 inR 4.3.0 if supported, and from R 4.4.0 only a C++17 compiler willbe selected as the default C++ compiler.

What standard a C++ compiler aims to support can be hard to determine:the value50 of__cplusplus may help butsome compilers use it to denote a standard which is partially supportedand some the latest standard which is (almost) fully supported. On aUnix-alikeconfigure will try to identify a compiler and flagsfor each of the standards: this relies heavily on the reported values of__cplusplus.

The webpagehttps://en.cppreference.com/w/cpp/compiler_supportgives some information on which compiler versions are known to supportrecent C++ features.

C++ standards have deprecated and later removed features. Be aware thatsome current compilers still accept removed features in C++17 mode,such asstd::unary_function (deprecated in C++11, removed in C++17).

For maximal portability a package should specify the standard itrequires for code in itssrc directory by including somethinglike ‘C++14’ in the ‘SystemRequirements’ field of theDESCRIPTION file, e.g.

SystemRequirements: C++14

If it has aMakevars file (orMakevars.win orMakevars.ucrt on Windows) this should include the line

CXX_STD = CXX14

On the other hand, specifying C++1151 when the code is valid under C++14 or C++17reduces future portability.

Code needing C++14 or later features can check for their presencevia‘SD-6 feature tests’52. Such a check could be

#include <memory> // header where this is defined#if defined(__cpp_lib_make_unique) && (__cpp_lib_make_unique >= 201304)using std::make_unique;#else// your emulation#endif

C++17, C++20, C++23 and C++26 (from R 4.5.0) can be specified in ananalogous way.

Note that C++17 or later ‘support’ does not mean complete support: usefeature tests as well as resources such ashttps://en.cppreference.com/w/cpp/compiler_support,https://gcc.gnu.org/projects/cxx-status.html andhttps://clang.llvm.org/cxx_status.html to see if the features youwant to use are widely implemented.

Attempts to specify an unknown C++ standard are silently ignored: recentversions of R throw an error for C++98 and for known standards forwhich no compiler+flags has been detected.

If a package using C++ has aconfigure script it is essentialthat the script selects the correct C++ compiler and standard,via something like

CXX17=`"${R_HOME}/bin/R" CMD config CXX17`if test -z "$CXX17"; then  AC_MSG_ERROR([No C++17 compiler is available])fiCXX17STD=`"${R_HOME}/bin/R" CMD config CXX17STD`CXX="${CXX17} ${CXX17STD}"CXXFLAGS=`"${R_HOME}/bin/R" CMD config CXX17FLAGS`## for an configure.ac fileAC_LANG(C++)

if C++17 was specified, but using

CXX=`"${R_HOME}/bin/R" CMD config CXX`CXXFLAGS=`"${R_HOME}/bin/R" CMD config CXXFLAGS`## for an configure.ac fileAC_LANG(C++)

if no standard was specified.

If you want to compile C++ code in a subdirectory, make sure you passdown the macros to specify the appropriate compiler, e.g. insrc/Makevars

sublibs:         @(cd libs && $(MAKE) \            CXX="$(CXX17) $(CXX17STD)" CXXFLAGS="$(CXX17FLAGS) $(CXX17PICFLAGS)")

The discussion above is about the standard R ways of compiling C++:it will not apply to packages usingsrc/Makefile or building in asubdirectory that do not set the C++ standard. Do not rely on thecompilers’ default C++ standard, which varies widely and gets changedfrequently by vendors – for example Apple clang up to at least 16defaults to C++98, LLVM clang 14–15 to C++14, LLVM clang 16–20andg++ 11–15 to C++17.

For a package with asrc/Makefile (or a Windows analogue),a non-default C++ compiler can be selected by including something like

CXX14 = `"${R_HOME}/bin/R" CMD config CXX14`CXX14STD = `"${R_HOME}/bin/R" CMD config CXX14STD`CXX = ${CXX14} ${CXX14STD}CXXFLAGS = `"${R_HOME}/bin/R" CMD config CXX14FLAGS`CXXPICFLAGS = `"${R_HOME}/bin/R" CMD config CXX14PICFLAGS`SHLIB_LD = "${R_HOME}/bin/R" CMD config SHLIB_CXX14LD`SHLIB_LDFLAGS = "${R_HOME}/bin/R" CMD config SHLIB_CXX14LDFLAGS`

and ensuring these values are used in relevant compilations, afterchecking they are non-empty. A common use ofsrc/Makefile is tocompile an executable, when likely something like (for example forC++14)

if test -z "$CXX14"; then  AC_MSG_ERROR([No C++14 compiler is available])fiCXX = ${CXX14} ${CXX14STD}CXXFLAGS = ${CXX14FLAGS}

suffices.

The.so/.dll in a package may need to be linked by theC++ compiler if it or any library it links to contains compiled C++code. Dynamic linking usually brings in the C++ runtime library(commonlylibstdc++ but can be, for example,libc++) butstatic linking (as used for external libraries on Windows and macOS)will not.R CMD INSTALL will link with the C++ compiler ifthere are any top-level C++ files insrc, but not if these areall in subdirectories. The simplest way to force linking by the C++compiler is to include an empty C++ file insrc..


Next:, Previous:, Up:Configure and cleanup   [Contents][Index]

1.2.5 C standards

C has had standards C89/C90, C99, C11, C17 (also known as C18), and C23(published in 2024). C11 was a minor change to C99 which introducedsome new features and made others optional, and C17 is a ‘bug-fix’update to C11. On the other hand, C23 makes extensive changes,including makingbool,true andfalse reservedwords, finally disallowing K&R-style function declarations and changingthe formerly deprecated meaning of function declarations with an emptyparameter list to now mean no parameters.53(There are many other additions: see for examplehttps://en.cppreference.com/w/c/23.)

As from R 4.5.0, R’sconfigure script chooses a compileroption which selects C23 if one is available. Some compilers (includinggcc 15) default to C23 and most others from 2022/3 andlater have such an option.

Theconfigure script in recent previous versions of R aimedto choose a C compiler which supported C11: as the default in recentversions ofgcc (prior to 15), LLVMclang andAppleclang is C17, that is what is likely to be chosen. Onthe other hand, until R 4.3.0 the makefiles for the Windows buildspecified C99 and up to R 4.4.3 used the compiler default which forthe recommended compiler was C17.

Packages may want to either avoid or embrace the changes in C23, and cando sovia specifying ‘USE_Cnn’ for 17, 23, 90 or 99 in the‘SystemRequirements’ field of theirDESCRIPTION file of apackage depending on ‘R (>= 4.3.0)’. Those using aconfigure script should set the corresponding compiler andflags, for example using

CC=`"${R_HOME}/bin/R" CMD config CC23`CFLAGS=`"${R_HOME}/bin/R" CMD config C23FLAGS`CPPFLAGS=`"${R_HOME}/bin/R" CMD config CPPFLAGS`LDFLAGS=`"${R_HOME}/bin/R" CMD config LDFLAGS`

However, not all platforms will have a C23 compiler: the first line herewill give an empty value if no C23 compiler was found.

The (claimed) C standard in use can be checked by the macro__STDC_VERSION__. This is undefined in C89/C90 and should havevalues199901L,201112L and201710L for C99, C11and C17. The definitive value for C23 is202311L but somecompilers54 are currently using202000L and requiring the standard tobe specified asc2x.C23 has macros similar to C++ ‘feature tests’ for many of its changes,for example__STDC_VERSION_LIMITS_H__.

However, note the ‘claimed’ as no compiler had 100% conformance, and itis better to useconfigure to test for the feature you want touse than to condition on the value of__STDC_VERSION__. Inparticular, C11 alignment functionality such as_Alignas andaligned_alloc is not implemented on Windows.

End users installing a source package can specify a standard bysomething likeR CMD INSTALL --use-C17. This overrides the‘SystemRequirements’ field, but not anyconfigure file.


Previous:, Up:Configure and cleanup   [Contents][Index]

1.2.6 Usingcmake

Packages often wish to include the sources of other software and compilethat for inclusion in their.so or.dll, which is normallydone by including (or unpacking) the sources in a subdirectory ofsrc, as considered above.

Further issues arise when the external software uses another buildsystem such ascmake, principally to ensure thatall the settings for compilers, include and load pathsetcare made. This section has already mentioned the need to setat least some of

CC CFLAGS CXX CXXFLAGS CPPFLAGS LDFLAGS

CFLAGS andCXXFLAGS will need to includeCPICFLAGSandCXXPICFLAGS respectively unless (as below)cmake isasked to generate PIC code.

Setting these (and more) as environment variables controls the behaviourofcmake(https://cmake.org/cmake/help/latest/manual/cmake-env-variables.7.html#manual:cmake-env-variables(7)),but it may be desirable to translate these into native settings such as

CMAKE_C_COMPILERCMAKE_C_FLAGSCMAKE_CXX_COMPILERCMAKE_CXX_FLAGSCMAKE_INCLUDE_PATHCMAKE_LIBRARY_PATHCMAKE_SHARED_LINKER_FLAGS_INITCMAKE_OSX_DEPLOYMENT_TARGET

and it is often necessary to ensure a static library of PIC code is built by

-DBUILD_SHARED_LIBS:bool=OFF-DCMAKE_POSITION_INDEPENDENT_CODE:bool=ON

If R is to be detected or used, this must be the build being used forpackage installation –"${R_HOME}"/bin/R.

To fix ideas, consider a package with sources for a librarymyLibundersrc/libs. Two approaches have been used. It is often mostconvenient to build the external software in a directory other than itssources (particularly during development when the build directory can beremoved between builds rather than attempting to clean the sources) –this is illustrated in the first approach.

  1. Use the package’sconfigure script to create a static librarysrc/build/libmyLib.a. This can then be treated in the same wayas external software, for example having insrc/Makevars
    PKG_CPPFLAGS = -Ilibs/includePKG_LIBS = build/libmyLib.a

    (-Lbuild -lmyLib could also be used but this explicitspecification avoids any confusion with dynamic libraries of the samename.)

    Theconfigure script will need to contain something like (for Ccode)

    : ${R_HOME=`R RHOME`}if test -z "${R_HOME}"; then  echo "could not determine R_HOME"  exit 1fiCC=`"${R_HOME}/bin/R" CMD config CC`CFLAGS=`"${R_HOME}/bin/R" CMD config CFLAGS`CPPFLAGS=`"${R_HOME}/bin/R" CMD config CPPFLAGS`LDFLAGS=`"${R_HOME}/bin/R" CMD config LDFLAGS`cd srcmkdir build && cd buildcmake -S ../libs \  -DCMAKE_BUILD_TYPE=Release \  -DBUILD_SHARED_LIBS:bool=OFF \  -DCMAKE_POSITION_INDEPENDENT_CODE:bool=ON${MAKE}
  2. Usesrc/Makevars (orsrc/Makevars.win orMakevars.ucrt) to build within thesubdirectory. This could be something like (for C code)
    PKG_CPPFLAGS = -Ilibs/includePKG_LIBS = libs/libmyLib.a$(SHLIB): mylibsmylibs:        (cd libs; \          CC="$(CC)" CFLAGS="$(CFLAGS)" \          CPPFLAGS="$(CPPFLAGS)" LDFLAGS="$(LDFLAGS)" \          cmake . \            -DCMAKE_BUILD_TYPE=Release \            -DBUILD_SHARED_LIBS:bool=OFF \            -DCMAKE_POSITION_INDEPENDENT_CODE:bool=ON; \          $(MAKE))

    the compiler and other settings having been set as Make variables by anR makefile included byINSTALL beforesrc/Makevars.

A complication is that on macOScmake (where installed) iscommonly not on the path but at/Applications/CMake.app/Contents/bin/cmake. One way to workaround this is for the package’sconfigure script to include

if test -z "$CMAKE"; then CMAKE="`which cmake`"; fiif test -z "$CMAKE"; then CMAKE=/Applications/CMake.app/Contents/bin/cmake; fiif test -f "$CMAKE"; then echo "no 'cmake' command found"; exit 1; fi

and for the second approach to substituteCMAKE intosrc/Makevars. This also applies to the ancillary commandctest, if used.


Next:, Previous:, Up:Creating R packages   [Contents][Index]

1.3 Checking and building packages

Before using these tools, please check that your package can beinstalled.R CMD check willinter alia do this, but youmay get more detailed error messages doing the install directly.

If your package specifies an encoding in itsDESCRIPTION file,you should run these tools in a locale which makes use of that encoding:they may not work at all or may work incorrectly in other locales(although UTF-8 locales will most likely work).

Note:R CMD check andR CMD build run R processes with--vanilla in which none of the user’s startup files are read.If you needR_LIBS set (to find packages in a non-standardlibrary) you can set it in the environment: also you can use the checkand build environment files (as specified by the environment variablesR_CHECK_ENVIRON andR_BUILD_ENVIRON; if unset,files55~/.R/check.Renviron and~/.R/build.Renviron are used) to set environment variables whenusing these utilities.

Note to Windows users:R CMD build may make use of the Windows toolset(seeThe Windows toolset inR Installation and Administration)if present and in your path,and it is required for packages which need it to install (includingthose withconfigure.win,cleanup.win,configure.ucrtorcleanup.ucrt scripts or asrc directory) and e.g. need vignettes built.

You may need to set the environment variableTMPDIR to point to asuitable writable directory with a path not containing spaces – useforward slashes for the separators. Also, the directory needs to be ona case-honouring file system (some network-mounted file systems arenot).


Next:, Up:Checking and building packages   [Contents][Index]

1.3.1 Checking packages

UsingR CMD check, the R package checker, one can test whethersource R packages work correctly. It can be run on one ormore directories, or compressed packagetar archives withextension.tar.gz,.tgz,.tar.bz2 or.tar.xz.

It is strongly recommended that the final checks are run on atar archive prepared byR CMD build.

This runs a series of checks, including

  1. The package is installed. This will warn about missing cross-referencesand duplicate aliases in help files.
  2. The file names are checked to be valid across file systems and supportedoperating system platforms.
  3. The files and directories are checked for sufficient permissions(Unix-alikes only).
  4. The files are checked for binary executables, using a suitable versionoffile if available56. (There may berare false positives.)
  5. TheDESCRIPTION file is checked for completeness, and some of itsentries for correctness. Unless installation tests are skipped,checking is aborted if the package dependencies cannot be resolved atrun time. (You may need to setR_LIBS in the environment ifdependent packages are in a separate library tree.) One check is thatthe package name is not that of a standard package, nor one of thedefunct standard packages (‘ctest’, ‘eda’, ‘lqs’,‘mle’, ‘modreg’, ‘mva’, ‘nls’, ‘stepfun’ and‘ts’). Another check is that all packages mentioned inlibrary orrequires or from which theNAMESPACEfile imports or are calledvia:: or::: are listed(in ‘Depends’, ‘Imports’, ‘Suggests’): this is not anexhaustive check of the actual imports.
  6. Available index information (in particular, for demos and vignettes) ischecked for completeness.
  7. The package subdirectories are checked for suitable file names and fornot being empty. The checks on file names are controlled by the option--check-subdirs=value. This defaults to ‘default’,which runs the checks only if checking a tarball: the default can beoverridden by specifying the value as ‘yes’ or ‘no’. Further,the check on thesrc directory is only run if the packagedoes not contain aconfigure script (which corresponds to thevalue ‘yes-maybe’) and there is nosrc/Makefile orsrc/Makefile.in.

    To allow aconfigure script to generate suitable files, filesending in ‘.in’ will be allowed in theR directory.

    A warning is given for directory names that look like R package checkdirectories – many packages have been submitted toCRANcontaining these.

  8. The R files are checked for syntax errors. Bytes which arenon-ASCII are reported as warnings, but these should beregarded as errors unless it is known that the package will always beused in the same locale.
  9. It is checked that the package can be loaded, first with the usualdefault packages and then only with packagebase alreadyloaded. It is checked that the namespace can be loaded in an emptysession with only thebase namespace loaded. (Namespaces andpackages can be loaded very early in the session, before the defaultpackages are available, so packages should work then.)
  10. The R files are checked for correct calls tolibrary.dynam.Package startup functions are checked for correct argument lists and(incorrect) calls to functions which modify the search path orinappropriately generate messages. The R code is checked forpossible problems usingcodetools. In addition, it is checkedwhether S3 methods have all the arguments of the corresponding generic, andwhether the final argument of replacement functions is called‘value’. All foreign function calls (.C,.Fortran,.Call and.External calls) are tested to see if they haveaPACKAGE argument, and if not, whether the appropriate DLL mightbe deduced from the namespace of the package. Any other calls arereported. (The check is generous, and users may want to supplement thisby examining the output oftools::checkFF("mypkg", verbose=TRUE),especially if the intention were to always use aPACKAGEargument)
  11. TheRd files are checked for correct syntax and metadata,including the presence of the mandatory fields (\name,\alias,\title and\description). TheRd name andtitle are checked for being non-empty, and there is a check for missingcross-references (links).
  12. A check is made for missing documentation entries, such as undocumenteduser-level objects in the package.
  13. Documentation for functions, data sets, and S4 classes is checked forconsistency with the corresponding code.
  14. It is checked whether all function arguments given in\usagesections ofRd files are documented in the corresponding\arguments section.
  15. Thedata directory is checked for non-ASCII charactersand for the use of reasonable levels of compression.
  16. C, C++ and Fortran source and header files57 aretested for portable (LF-only) line endings. If there is aMakefile orMakefile.in orMakevars orMakevars.in file under thesrc directory, it is checkedfor portable line endings and the correct use of ‘$(BLAS_LIBS)’ and‘$(LAPACK_LIBS)

    Compiled code is checked for symbols corresponding to functions whichmight terminate R or write tostdout/stderr instead ofthe console. Note that the latter might give false positives in thatthe symbols might be pulled in with external libraries and could neverbe called. Windows58 usersshould note that the Fortran and C++ runtime libraries are examples ofsuch external libraries.

  17. Some checks are made of the contents of theinst/doc directory.These always include checking for files that look like leftovers, and ifsuitable tools (such asqpdf) are available, checking that thePDF documentation is of minimal size.
  18. The examples provided by the package’s documentation are run.(seeWriting R documentation files, for information on using\examples to create executable example code.) If there is a filetests/Examples/pkg-Ex.Rout.save, the output of running theexamples is compared to that file.

    Of course, released packages should be able to run at least their ownexamples. Each example is run in a ‘clean’ environment (so earlierexamples cannot be assumed to have been run), and with the variablesT andF redefined to generate an error unless they are setin the example:SeeLogical vectors inAn Introduction to R.

  19. If the package sources contain atests directory then the testsspecified in that directory are run. (Typically they will consist of aset of.R source files and target output files.Rout.save.) Please note that the comparison will be done in theend user’s locale, so the target output files should beASCIIif at all possible. (The command line option--test-dir=foo maybe used to specify tests in a non-standard location. For example,unusually slow tests could be placed ininst/slowTests and thenR CMD check --test-dir=inst/slowTests would be used to run them.Other names that have been suggested are, for example,inst/testWithOracle for tests that require Oracle to be installed,inst/randomTests for tests which use random values and mayoccasionally fail by chance, etc.)
  20. The R code in package vignettes (seeWriting package vignettes) isexecuted, and the vignettes re-made from their sources as a check ofcompleteness of the sources (unless there is a ‘BuildVignettes’field in the package’sDESCRIPTION file with a false value). Ifthere is a target output file.Rout.save in the vignette sourcedirectory, the output from running the code in that vignette is comparedwith the target output file and any differences are reported (but notrecorded in the log file). (If the vignette sources are in thedeprecated locationinst/doc, do mark such target output files tonot be installed in.Rinstignore.)

    If there is an error59 in executing the R code in vignettefoo.ext, a logfilefoo.ext.log is created in the check directory. Thevignettes are re-made in a copy of the package sources in thevign_test subdirectory of the check directory, so for furtherinformation on errors look in directorypkgname/vign_test/vignettes. (It is only retained if thereare errors or if environment variable_R_CHECK_CLEAN_VIGN_TEST_ isset to a false value.)

  21. The PDF version of the package’s manual is created (to check that theRd files can be converted successfully). This needs LaTeX andsuitable fonts and LaTeX packages to be installed.SeeMaking the manuals inR Installation and Administrationfor further details.
  22. Optionally (including byR CMD check --as-cran) the HTMLversion of the manual is created and checked for compliance with theHTML5 standard. This requires a recent version60 of ‘HTMLTidy’, either on the path or at a location specified by environmentvariableR_TIDYCMD. Up-to-date versions can be installed fromhttp://binaries.html-tidy.org/.

All these tests are run with collation set to theC locale, andfor the examples and tests with environment variableLANGUAGE=en:this is to minimize differences between platforms.

UseR CMD check --help to obtain more information about the usageof the R package checker. A subset of the checking steps can beselected by adding command-line options. It also allows customization bysetting environment variables_R_CHECK_*_ as described inTools inR Internals:a set of these customizations similar to those used byCRANcan be selected by the option--as-cran (which works best ifInternet access is available). Some Windows users mayneed to set environment variableR_WIN_NO_JUNCTIONS to a non-emptyvalue. The test of cyclic declarations61inDESCRIPTION files needsrepositories (includingCRAN) set: do this in~/.Rprofile, by e.g.

options(repos = c(CRAN="https://cran.r-project.org"))

One check customization which can be revealing is

_R_CHECK_CODETOOLS_PROFILE_="suppressLocalUnused=FALSE"

which reports unused local assignments. Not only does this point outcomputations which are unnecessary because their results are unused, italso can uncover errors. (Two such are to intend to update an object byassigning a value but mistype its name or assign in the wrong scope,for example using<- where<<- was intended.) This cangive false positives, most commonly because of non-standard evaluationfor formulae and because the intention is to return objects in theenvironment of a function for later use.

Complete checking of a package which contains a fileREADME.mdneeds a reasonably current version ofpandoc installed: seehttps://pandoc.org/installing.html.

You do need to ensure that the package is checked in a suitable localeif it contains non-ASCII characters. Such packages are likelyto fail some of the checks in aC locale, andR CMDcheck will warn if it spots the problem. You should be able to checkany package in a UTF-8 locale (if one is available). Beware thatalthough aC locale is rarely used at a console, it may be thedefault if logging in remotely or for batch jobs.

OftenR CMD check will need to consult a CRAN repository tocheck details of uninstalled packages. Normally this defaults to theCRAN main site, but a mirror can be specified by setting environmentvariablesR_CRAN_WEB and (rarely needed)R_CRAN_SRC to theURL of a CRAN mirror.

It is possible to install a package and then check the installedpackage. To do so first install the package and keep a log of theinstallation:

R CMD INSTALL -llibdirpkg >pkg.log 2>&1

and then use

Rdev CMD check -llibdir --install=check:pkg.logpkg

(Specifying the library is required: it ensures that the just-installedpackage is the one checked. If you know for sure only one copy isinstalled you can use--install=skip: this is used for Rinstallation’smake check-recommended.)


Next:, Previous:, Up:Checking and building packages   [Contents][Index]

1.3.2 Building package tarballs

Packages may be distributed in source form as “tarballs”(.tar.gz files) or in binary form. The source form can beinstalled on all platforms with suitable tools and is the usual form forUnix-like systems; the binary form is platform-specific, and is the morecommon distribution form for the macOS and ‘x86_64’ Windows platforms.

UsingR CMD build, the R package builder, one can buildR package tarballs from their sources (for example, for subsequentrelease). It is recommended that packages are built for release by thecurrent release version of R or ‘r-patched’, to avoidinadvertently picking up new features of a development version of R.

Prior to actually building the package in the standard gzipped tar fileformat, a few diagnostic checks and cleanups are performed. Inparticular, it is tested whether object indices exist and can be assumedto be up-to-date, and C, C++ and Fortran source files and relevantmakefiles in asrc directory are tested and converted toLFline-endings if necessary.

Run-time checks whether the package works correctly should be performedusingR CMD check prior to invoking the final build procedure.

To exclude files from being put into the package, one can specify a listof exclude patterns in file.Rbuildignore in the top-level sourcedirectory. These patterns should be Perl-like regular expressions (seethe help forregexp in R for the precise details), one perline, to be matched case-insensitively against the file and directorynames relative to the top-level package source directory. In addition,directories from source control systems62 or fromeclipse63, directories withnamescheck,chm, or ending.Rcheck orOldorold and filesGNUMakefile64,Read-and-delete-me or with base namesstarting with ‘.#’, or starting and ending with ‘#’, or endingin ‘~’, ‘.bak’ or ‘.swp’, are excluded bydefault65. In addition,same-package tarballs (from previous builds) and their binary forms willbe excluded from the top-level directory, as well asthose files in theR,demo andmandirectories which are flagged byR CMD check as having invalidnames.

UseR CMD build --help to obtain more information about the usageof the R package builder.

UnlessR CMD build is invoked with the--no-build-vignettes option (or the package’sDESCRIPTION contains ‘BuildVignettes: no’ or similar), itwill attempt to (re)build the vignettes (seeWriting package vignettes) in the package. To do so it installs the current packageinto a temporary library tree, but any dependent packages need to beinstalled in an available library tree (see the Note: at the top of thissection).

Similarly, if the.Rd documentation files contain any\Sexpr macros (seeDynamic pages), the package will betemporarily installed to execute them. Post-execution binary copies ofthose pages containing build-time macros will be saved inbuild/partial.rdb. If there are any install-time or render-timemacros, a.pdf version of the package manual will be built andinstalled in thebuild subdirectory. (This allowsCRAN or other repositories to display the manual even if theyare unable to install the package.) This can be suppressed by theoption--no-manual or if package’sDESCRIPTION contains‘BuildManual: no’ or similar.

One of the checks thatR CMD build runs is for empty sourcedirectories. These are in most (but not all) cases unintentional, ifthey are intentional use the option--keep-empty-dirs (or setthe environment variable_R_BUILD_KEEP_EMPTY_DIRS_ to ‘TRUE’,or have a ‘BuildKeepEmpty’ field with a true value in theDESCRIPTION file).

The--resave-data option allows saved images (.rda and.RData files) in thedata directory to be optimized forsize. It will also compress tabular files and convert.R filesto saved images. It can take valuesno,gzip (the defaultif this option is not supplied, which can be changed by setting theenvironment variable_R_BUILD_RESAVE_DATA_) andbest(equivalent to giving it without a value), which chooses the mosteffective compression. Usingbest adds a dependence onR(>= 2.10) to theDESCRIPTION file ifbzip2 orxz compression is selected for any of the files. If this isthought undesirable,--resave-data=gzip (which is the defaultif that option is not supplied) will do what compression it can withgzip. A package can control how its data is resaved bysupplying a ‘BuildResaveData’ field (with one of the values givenearlier in this paragraph) in itsDESCRIPTION file.

The--compact-vignettes option will runtools::compactPDF over the PDF files ininst/doc (and itssubdirectories) to losslessly compress them. This is not enabled bydefault (it can be selected by environment variable_R_BUILD_COMPACT_VIGNETTES_) and needsqpdf(https://qpdf.sourceforge.io/) to be available.

It can be useful to runR CMD check --check-subdirs=yes on thebuilt tarball as a final check on the contents.

Where a non-POSIX file system is in use which does not utilize executepermissions, some care is needed with permissions. This applies onWindows and to e.g. FAT-formatted drives and SMB-mounted file systemson other OSes. The ‘mode’ of the file recorded in the tarball will bewhateverfile.info() returns. On Windows this will record onlydirectories as having execute permission and on other OSes it is likelythat all files have reported ‘mode’0777. A particular issue ispackages being built on Windows which are intended to contain executablescripts such asconfigure andcleanup:R CMDbuild ensures those two are recorded with execute permission.

Directorybuild of the package sources is reserved for use byR CMD build: it contains information which may not easily becreated when the package is installed, including index information onthe vignettes and, rarely, information on the help pages and perhaps acopy of the PDF reference manual (see above).


Previous:, Up:Checking and building packages   [Contents][Index]

1.3.3 Building binary packages

Binary packages are compressed copies of installed versions ofpackages. They contain compiled shared libraries rather than C, C++ orFortran source code, and the R functions are included in their installedform. The format and filename are platform-specific; for example, abinary package for Windows is usually supplied as a.zip file,and for the macOS platform the default binary package file extension is.tgz.

The recommended method of building binary packages is to use

R CMD INSTALL --build pkg

wherepkg is either the name of a source tarball (in the usual.tar.gz format) or the location of the directory of the packagesource to be built. This operates by first installing the package andthen packing the installed binaries into the appropriate binary packagefile for the particular platform.

By default,R CMD INSTALL --build will attempt to install thepackage into the default library tree for the local installation ofR. This has two implications:

  • If the installation is successful, it will overwrite any existing installationof the same package.
  • The default library tree must have write permission; if not, the package willnot install and the binary will not be created.

To prevent changes to the present working installation or to provide aninstall location with write access, create a suitably located directorywith write access and use the-l option to build the packagein the chosen location. The usage is then

R CMD INSTALL -l location --build pkg

wherelocation is the chosen directory with write access. The packagewill be installed as a subdirectory oflocation, and the package binarywill be created in the current directory.

Other options forR CMD INSTALL can be found usingRCMD INSTALL --help, and platform-specific details for special cases arediscussed in the platform-specific FAQs.

Finally, at least one web-based service is available for building binarypackages from (checked) source code: WinBuilder (seehttps://win-builder.R-project.org/) is able to build‘x86_64’ Windows binaries. Note that this is intended fordevelopers on other platforms who do not have access to Windows but wishto provide binaries for the Windows platform.


Next:, Previous:, Up:Creating R packages   [Contents][Index]

1.4 Writing package vignettes

In addition to the help files inRd format, R packages allowthe inclusion of documents in arbitrary other formats. The standardlocation for these is subdirectoryinst/doc of a source package,the contents will be copied to subdirectorydoc when the packageis installed. Pointers from package help indices to the installeddocuments are automatically created. Documents ininst/doc canbe in arbitrary format, however we strongly recommend providing them inPDF format, so users on almost all platforms can easily read them. Toensure that they can be accessed from a browser (as anHTML index isprovided), the file names should start with anASCII letterand be comprised entirely ofASCII letters or digits or hyphenor underscore.

A special case ispackage vignettes. Vignettes are documents inPDF orHTML format obtained from plain-text literate source filesfrom which R knows how to extract R code and create output (inPDF/HTML or intermediate LaTeX). Vignette engines do this work,using “tangle” and “weave” functions respectively. Sweave, providedby the R distribution, is the default engine. Other vignette enginesbesides Sweave are supported; seeNon-Sweave vignettes.

Package vignettes have their sources in subdirectoryvignettes ofthe package sources. Note that the location of the vignette sourcesonly affectsR CMD build andR CMD check: thetarball built byR CMD build includes ininst/doc thecomponents intended to be installed.

Sweave vignette sources are normally given the file extension.Rnw or.Rtex, but for historical reasonsextensions66.Snw and.Stex are also recognized. Sweave allows the integration ofLaTeX documents: see theSweave help page in R and theSweave vignette in packageutils for details on thesource document format.

Package vignettes are tested byR CMD check by executing all Rcode chunks they contain (except those marked for non-evaluation, e.g.,with optioneval=FALSE for Sweave). The R working directoryfor all vignette tests inR CMD check is acopy of thevignette source directory. Make sure all files needed to run the Rcode in the vignette (data sets, …) are accessible by eitherplacing them in theinst/doc hierarchy of the source package orby using calls tosystem.file(). All other files needed tore-make the vignettes (such as LaTeX style files, BibTeX inputfiles and files for any figures not created by running the code in thevignette) must be in the vignette source directory.R CMD checkwill check that vignette production has succeeded by comparingmodification times of output files ininst/doc withthe source invignettes.

R CMD build will automatically67 create the(PDF orHTML versions of the) vignettes ininst/doc fordistribution with the package sources. By including the vignetteoutputs in the package sources it is not necessary that these can bere-built at install time, i.e., the package author can use private Rpackages, screen snapshots and LaTeX extensions which are onlyavailable on their machine.68

By defaultR CMD build will runSweave on all Sweavevignette source files invignettes. IfMakefile is foundin the vignette source directory, thenR CMD build will try torunmake after theSweave runs, otherwisetexi2pdf is run on each.tex file produced.

The first target in theMakefile should take care of bothcreation of PDF/HTML files and cleaning up afterwards (includingafterSweave), i.e., delete all files that shall not appear inthe final package archive. Note that if themake step runs Rit needs to be careful to respect the environment values ofR_LIBSandR_HOME69.Finally, if there is aMakefile and it has a ‘clean:’target,make clean is run.

All the usualcaveats about including aMakefile apply.It must be portable (noGNU extensions), useLF line endingsand must work correctly with a parallelmake: too many authorshave written things like

## BAD EXAMPLEall: pdf cleanpdf: ABC-intro.pdf ABC-details.pdf%.pdf:  %.tex        texi2dvi --pdf $*clean:        rm *.tex ABC-details-*.pdf

which will start removing the source files whilstpdflatex isworking.

Metadata lines can be placed in the source file, preferably in LaTeXcomments in the preamble. One such is a\VignetteIndexEntry ofthe form

%\VignetteIndexEntry{Using Animal}

Others you may see are\VignettePackage (currently ignored),\VignetteDepends (a comma-separated list of package names)and\VignetteKeyword (which replaced\VignetteKeywords). These are processed at package installationtime to create the saved data frameMeta/vignette.rds.The\VignetteEngine statementis described inNon-Sweave vignettes.Vignette metadata can be extracted from a source file usingtools::vignetteInfo.

At install time anHTML index for all vignettes in the package isautomatically created from the\VignetteIndexEntry statementsunless a fileindex.html exists in directoryinst/doc. This index is linked from theHTML help index forthe package. If you do supply ainst/doc/index.html file itshould contain relative links only to files under the installeddoc directory, or perhaps (not really an index) toHTML helpfiles or to theDESCRIPTION file, and be validHTML asconfirmedvia theW3C MarkupValidation Service orValidator.nu.

Sweave/Stangle allows the document to specify thesplit=TRUEoption to create a single R file for each code chunk: this will notwork for vignettes where it is assumed that each vignette sourcegenerates a single file with the vignette extension replaced by.R.

Do watch that PDFs are not too large – one in aCRAN packagewas 72MB! This is usually caused by the inclusion of overly detailedfigures, which will not render well in PDF viewers. Sometimes it ismuch better to generate fairly high resolution bitmap (PNG, JPEG)figures and include those in the PDF document.

WhenR CMD build builds the vignettes, it copies these andthe vignette sources from directoryvignettes toinst/doc.To install any other files from thevignettes directory, includea filevignettes/.install_extras which specifies these asPerl-like regular expressions on one or more lines. (See thedescription of the.Rinstignore file for full details.)


Next:, Up:Writing package vignettes   [Contents][Index]

1.4.1 Encodings and vignettes

Vignettes will in general include descriptive text, R input, Routput and figures, LaTeX include files and bibliographic references.As any of these may contain non-ASCII characters, the handlingof encodings can become very complicated.

The vignette source file should be written inASCII or containa declaration of the encoding (see below). This applies even tocomments within the source file, since vignette engines process commentsto look for options and metadata lines. When an engine’s weave andtangle functions are called on the vignette source, it will be convertedto the encoding of the current R session.

Stangle() will produce an R code file in the current locale’sencoding: for a non-ASCII vignette what that is is recorded in acomment at the top of the file.

Sweave() will produce a.tex file in the currentencoding, or in UTF-8 if that is declared. Non-ASCII encodingsneed to be declared to LaTeX via a line like

\usepackage[utf8]{inputenc}

(It is also possible to use the more recent ‘inputenx’ LaTeXpackage.) For files where this line is not needed (e.g. chaptersincluded within the body of a larger document, or non-Sweavevignettes), the encoding may be declared using a comment like

%\VignetteEncoding{UTF-8}

If the encoding is UTF-8, this can also be declared usingthe declaration

%\SweaveUTF8

If no declaration is given in the vignette, it will be assumed to bein the encoding declared for the package. If there is no encodingdeclared in either place, then it is an error to use non-ASCIIcharacters in the vignette.

In any case, be aware that LaTeX may require the ‘usepackage’declaration.

Sweave() will also parse and evaluate the R code in eachchunk. The R output will also be in the current locale (orUTF-8if so declared), and shouldbe covered by the ‘inputenc’ declaration. One thing people oftenforget is that the R output may not beASCII even forASCII R sources, for many possible reasons. One common oneis the use of ‘fancy’ quotes: see the R help onsQuote: notecarefully that it is not portable to declare UTF-8 or CP1252 to coversuch quotes, as their encoding will depend on the locale used to runSweave(): this can be circumvented by settingoptions(useFancyQuotes="UTF-8") in the vignette.

The final issue is the encoding of figures – this applies only to PDFfigures and not PNG etc. The PDF figures will contain declarations fortheir encoding, but the Sweave optionpdf.encoding may need to beset appropriately: see the help for thepdf() graphics device.

As a real example of the complexities, consider thefortunespackage version ‘1.4-0’. That package did not have a declaredencoding, and its vignette was inASCII. However, the data itdisplays are read from a UTF-8 CSV file and will be assumed to be in thecurrent encoding, sofortunes.tex will be in UTF-8 in any locale.Hadread.table been told the data were UTF-8,fortunes.texwould have been in the locale’s encoding.


Previous:, Up:Writing package vignettes   [Contents][Index]

1.4.2 Non-Sweave vignettes

Vignettes in formats other than Sweave are supportedvia“vignette engines”. For exampleknitr version 1.1 or latercan create.tex files from a variation on Sweave format, and.html files from a variation on “markdown” format. Theseengines replace theSweave() function with other functions toconvert vignette source files into LaTeX files for processing into.pdf, or directly into.pdf or.html files. TheStangle() function is replaced with a function that extracts theR source from a vignette.

R recognizes non-Sweave vignettes using filename extensions specifiedby the engine. For example, theknitr package supportsthe extension.Rmd (standing for“R markdown”). The user indicates the vignette enginewithin the vignette source using a\VignetteEngine line, for example

%\VignetteEngine{knitr::knitr}

This specifies the name of a package and an engine to use in place ofSweave in processing the vignette. AsSweave is the only enginesupplied with the R distribution, the package providing any otherengine must be specified in the ‘VignetteBuilder’ field of thepackageDESCRIPTION file, and also specified in the‘Suggests’, ‘Imports’ or ‘Depends’ field (since itsnamespace must be available to build or check your package). If morethan one package is specified as a builder, they will be searched in theorder given there. Theutils package is always implicitlyappended to the list of builder packages, but may be included earlierto change the search order.

Note that a package with non-Sweave vignettes should always have a‘VignetteBuilder’ field in theDESCRIPTION file, since thisis howR CMD check recognizes that there are vignettes to bechecked: packages listed there are required when the package is checked.

The vignette engine can produce.tex,.pdf, or.htmlfiles as output. If it produces.tex files, R willcalltexi2pdf to convert them to.pdf for displayto the user (unless there is aMakefile in thevignettesdirectory).

Package writers who would like to supply vignette engines needto register those engines in the package.onLoad function.For example, that function could make the call

tools::vignetteEngine("knitr", weave = vweave, tangle = vtangle,                      pattern = "[.]Rmd$", package = "knitr")

(The actual registration inknitr is more complicated, becauseit supports other input formats.) See the?tools::vignetteEnginehelp topic for details on engine registration.


Next:, Previous:, Up:Creating R packages   [Contents][Index]

1.5 Package namespaces

R has a namespace management system for code in packages. Thissystem allows the package writer to specify which variables in thepackage should beexported to make them available to packageusers, and which variables should beimported from otherpackages.

The namespace for a package is specified by theNAMESPACE file in the top level package directory. This filecontainsnamespace directives describing the imports and exportsof the namespace. Additional directives register any shared objects tobe loaded and any S3-style methods that are provided. Note thatalthough the file looks like R code (and often has R-stylecomments) it is not processed as R code. Only very simpleconditional processing ofif statements is implemented.

Packages are loaded and attached to the search path by callinglibrary orrequire. Only the exported variables areplaced in the attached frame. Loading a package that imports variablesfrom other packages will cause these other packages to be loaded as well(unless they have already been loaded), but they willnot beplaced on the search path by these implicit loads. Thus code in thepackage can only depend on objects in its own namespace and its imports(including thebase namespace) being visible70.

Namespaces aresealed once they are loaded. Sealing means thatimports and exports cannot be changed and that internal variablebindings cannot be changed. Sealing allows a simpler implementationstrategy for the namespace mechanism and allows code analysis andcompilation tools to accurately identify the definition corresponding toa global variable reference in a function body.

The namespace controls the search strategy for variables used byfunctions in the package. If not found locally, R searches thepackage namespace first, then the imports, then the base namespace andthen the normal search path (so the base namespace precedes the normalsearch rather than being at the end of it).


Next:, Up:Package namespaces   [Contents][Index]

1.5.1 Specifying imports and exports

Exports are specified using theexport directive in theNAMESPACE file. A directive of the form

export(f, g)

specifies that the variablesf andg are to be exported.(Note that variable names may be quoted, and reserved words andnon-standard names such as[<-.fractions must be.)

For packages with many variables to export it may be more convenient tospecify the names to export with a regular expression usingexportPattern. The directive

exportPattern("^[^.]")

exports all variables that do not start with a period. However, suchbroad patterns are not recommended for production code: it is better tolist all exports or use narrowly-defined groups. (This pattern appliesto S4 classes.) Beware of patterns which include names starting with aperiod: some of these are internal-only variables and should never beexported, e.g. ‘.__S3MethodsTable__.’ (and loading excludes knowncases).

Packages implicitly import the base namespace.Variables exported from other packages with namespaces need to beimported explicitly using the directivesimport andimportFrom. Theimport directive imports all exportedvariables from the specified package(s). Thus the directives

import(foo, bar)

specifies that all exported variables in the packagesfoo andbar are to be imported. If only some of the exported variablesfrom a package are needed, then they can be imported usingimportFrom. The directive

importFrom(foo, f, g)

specifies that the exported variablesf andg of thepackagefoo are to be imported. UsingimportFromselectively rather thanimport is good practice and recommendednotably when importing from packages with more than a dozen exports andespecially from those written by others (so what they export can changein future).

To import every symbol from a package but for a few exceptions,pass theexcept argument toimport. The directive

import(foo, except=c(bar, baz))

imports every symbol fromfoo exceptbar andbaz. The value ofexcept should evaluate to somethingcoercible to a character vector, after substituting each symbol forits corresponding string.

It is possible to export variables from a namespace which it hasimported from other namespaces: this has to be done explicitly and notviaexportPattern.

If a package only needs a few objects from another package it can use afully qualified variable reference in the code instead of a formalimport. A fully-qualified reference to the functionf in packagefoo is of the formfoo::f. This is slightly less efficientthan a formal import and also loses the advantage of recording alldependencies in theNAMESPACE file (but they still need to berecorded in theDESCRIPTION file). Evaluatingfoo::f willcause packagefoo to be loaded, but not attached, if it was notloaded already—this can be an advantage in delaying the loading of ararely used package. However, iffoo is listed only in‘Suggests’ or ‘Enhances’ this also delays the check that it isinstalled: it is good practice to use such imports conditionally (e.g.viarequireNamespace("foo", quietly = TRUE)).

Using thefoo::f form will be necessary when a package needs touse a function of the same name from more than one namespace.

Usingfoo:::f instead offoo::f allows access tounexported objects. This is generally not recommended, as the existenceor semantics of unexported objects may be changed by the package authorin routine maintenance.


Next:, Previous:, Up:Package namespaces   [Contents][Index]

1.5.2 Registering S3 methods

The standard method for S3-styleUseMethod dispatching might failto locate methods defined in a package that is imported but not attachedto the search path. To ensure that these methods are available thepackages defining the methods should ensure that the generics areimported and register the methods usingS3method directives. Ifa package defines a functionprint.foo intended to be used as aprint method for classfoo, then the directive

S3method(print, foo)

ensures that the method is registered and available forUseMethoddispatch, and the functionprint.foo does not need to be exported.Since the genericprint is defined inbase it does not needto be imported explicitly.

(Note that function and class names may be quoted, and reserved wordsand non-standard names such as[<- andfunction mustbe.)

It is possible to specify a third argument to S3method, the function tobe used as the method, for example

S3method(print, check_so_symbols, .print.via.format)

whenprint.check_so_symbols is not needed.

As from R 3.6.0 one can also useS3method() directives toperformdelayed registration. With

if(getRversion() >= "3.6.0") {    S3method(pkg::gen, cls)}

functiongen.cls will get registered as an S3 method for classcls and genericgen from packagepkg only when thenamespace ofpkg is loaded. This can be employed to deal withsituations where the method is not “immediately” needed, and having topre-load the namespace ofpkg (and all its strong dependencies)in order to perform immediate registration is considered too onerous.


Next:, Previous:, Up:Package namespaces   [Contents][Index]

1.5.3 Load hooks

There are a number of hooks called as packages are loaded, attached,detached, and unloaded. Seehelp(".onLoad") for more details.

Since loading and attaching are distinct operations, separate hooks areprovided for each. These hook functions are called.onLoad and.onAttach. They both take arguments71libname andpkgname; they should be defined in the namespace but notexported.

Packages can use a.onDetach or.Last.lib function(provided the latter is exported from the namespace) whendetachis called on the package. It is called with a single argument, the fullpath to the installed package. There is also a hook.onUnloadwhich is called when the namespace is unloaded (via a call tounloadNamespace, perhaps called bydetach(unload = TRUE))with argument the full path to the installed package’s directory.Functions.onUnload and.onDetach should be defined in thenamespace and not exported, but.Last.lib does need to beexported.

Packages are not likely to need.onAttach (except perhaps for astart-up banner); code to set options and load shared objects should beplaced in a.onLoad function, or use made of theuseDynLibdirective described next.

User-level hooks are also available: see the help on functionsetHook.

These hooks are often used incorrectly. People forget to export.Last.lib. Compiled code should be loaded in.onLoad (orvia auseDynLb directive: see below) and unloaded in.onUnload. Do remember that a package’s namespace can be loadedwithout the namespace being attached (e.g. bypkgname::fun) andthat a package can be detached and re-attached whilst its namespaceremains loaded.

It is good practice for these functions to be quiet. Any messagesshould usepackageStartupMessage so users (include check scripts)can suppress them if desired.


Next:, Previous:, Up:Package namespaces   [Contents][Index]

1.5.4useDynLib

ANAMESPACE file can contain one or moreuseDynLibdirectives which allows shared objects that need to beloaded.72 The directive

useDynLib(foo)

registers the shared objectfoo73 for loading withlibrary.dynam.Loading of registered object(s) occurs after the package code has beenloaded and before running the load hook function. Packages that wouldonly need a load hook function to load a shared object can use theuseDynLib directive instead.

TheuseDynLib directive also accepts the names of the nativeroutines that are to be used in Rvia the.C,.Call,.Fortran and.External interface functions. These are given asadditional arguments to the directive, for example,

useDynLib(foo, myRoutine, myOtherRoutine)

By specifying these names in theuseDynLib directive, the nativesymbols are resolved when the package is loaded and R variablesidentifying these symbols are added to the package’s namespace withthese names. These can be used in the.C,.Call,.Fortran and.External calls in place of the name of theroutine and thePACKAGE argument. For instance, we can call theroutinemyRoutine from R with the code

 .Call(myRoutine, x, y)

rather than

 .Call("myRoutine", x, y, PACKAGE = "foo")

There are at least two benefits to this approach. Firstly, the symbollookup is done just once for each symbol rather than each time theroutine is invoked. Secondly, this removes any ambiguity in resolvingsymbols that might be present in more than one DLL. However, thisapproach is nowadays deprecated in favour of supplying registrationinformation (see below).

In some circumstances, there will already be an R variable in thepackage with the same name as a native symbol. For example, we may havean R function in the package namedmyRoutine. In this case,it is necessary to map the native symbol to a different R variablename. This can be done in theuseDynLib directive by using namedarguments. For instance, to map the native symbol namemyRoutineto the R variablemyRoutine_sym, we would use

useDynLib(foo, myRoutine_sym = myRoutine, myOtherRoutine)

We could then call that routine from R using the command

 .Call(myRoutine_sym, x, y)

Symbols without explicit names are assigned to the R variable withthat name.

In some cases, it may be preferable not to create R variables in thepackage’s namespace that identify the native routines. It may be toocostly to compute these for many routines when the package is loadedif many of these routines are not likely to be used. In this case,one can still perform the symbol resolution correctly using the DLL,but do this each time the routine is called. Given a reference to theDLL as an R variable, saydll, we can call the routinemyRoutine using the expression

 .Call(dll$myRoutine, x, y)

The$ operator resolves the routine with the given name in theDLL using a call togetNativeSymbol. This is the samecomputation as above where we resolve the symbol when the package isloaded. The only difference is that this is done each time in the caseofdll$myRoutine.

In order to use this dynamic approach (e.g.,dll$myRoutine), oneneeds the reference to the DLL as an R variable in the package. TheDLL can be assigned to a variable by using thevariable =dllName format used above for mapping symbols to R variables. Forexample, if we wanted to assign the DLL reference for the DLLfoo in the example above to the variablemyDLL, we woulduse the following directive in theNAMESPACE file:

myDLL = useDynLib(foo, myRoutine_sym = myRoutine, myOtherRoutine)

Then, the R variablemyDLL is in the package’s namespace andavailable for calls such asmyDLL$dynRoutine to access routinesthat are not explicitly resolved at load time.

If the package has registration information (seeRegistering native routines), then we can use that directly rather than specifying thelist of symbols again in theuseDynLib directive in theNAMESPACE file. Each routine in the registration information isspecified by giving a name by which the routine is to be specified alongwith the address of the routine and any information about the number andtype of the parameters. Using the.registration argument ofuseDynLib, we can instruct the namespace mechanism to createR variables for these symbols. For example, suppose we have thefollowing registration information for a DLL namedmyDLL:

static R_NativePrimitiveArgType foo_t[] = {    REALSXP, INTSXP, STRSXP, LGLSXP};static const R_CMethodDef cMethods[] = {   {"foo", (DL_FUNC) &foo, 4, foo_t},   {"bar_sym", (DL_FUNC) &bar, 0},   {NULL, NULL, 0, NULL}};static const R_CallMethodDef callMethods[] = {   {"R_call_sym", (DL_FUNC) &R_call, 4},   {"R_version_sym", (DL_FUNC) &R_version, 0},   {NULL, NULL, 0}};

Then, the directive in theNAMESPACE file

useDynLib(myDLL, .registration = TRUE)

causes the DLL to be loaded and also for the R variablesfoo,bar_sym,R_call_sym andR_version_sym to bedefined in the package’s namespace.

Note that the names for the R variables are taken from the entry inthe registration information and do not need to be the same as the nameof the native routine. This allows the creator of the registrationinformation to map the native symbols to non-conflicting variable namesin R, e.g.R_version toR_version_sym for use in anR function such as

R_version <- function(){  .Call(R_version_sym)}

Using argument.fixes allows an automatic prefix to be added tothe registered symbols, which can be useful when working with anexisting package. For example, packageKernSmooth has

useDynLib(KernSmooth, .registration = TRUE, .fixes = "F_")

which makes the R variables corresponding to the Fortran symbolsF_bkde and so on, and so avoid clashes with R code in thenamespace.

NB: Using these arguments for a package which does not registernative symbols merely slows down the package loading (although manyCRAN packages have done so). Once symbols are registered,check that the corresponding R variables are not accidentallyexported by a pattern in theNAMESPACE file.


Next:, Previous:, Up:Package namespaces   [Contents][Index]

1.5.5 An example

As an example consider two packages namedfoo andbar. TheR code for packagefoo in filefoo.R is

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

Some C code defines a C function compiled into DLLfoo (with anappropriate extension). TheNAMESPACE file for this package is

useDynLib(foo)export(f, foo)S3method(print, foo)

The second packagebar has code filebar.R

c <- function(...) sum(...)g <- function(y) f(c(y, 7))h <- function(y) y+9

andNAMESPACE file

import(foo)export(g, h)

Callinglibrary(bar) loadsbar and attaches its exports tothe search path. Packagefoo is also loaded but not attached tothe search path. A call tog produces

> g(6)[1]  1 13

This is consistent with the definitions ofc in the two settings:inbar the functionc is defined to be equivalent tosum, but infoo the variablec refers to thestandard functionc inbase.


Previous:, Up:Package namespaces   [Contents][Index]

1.5.6 Namespaces with S4 classes and methods

Some additional steps are needed for packages which make use of formal(S4-style) classes and methods (unless these are purely usedinternally). The package should haveDepends: methods74 in itsDESCRIPTION andimport(methods) orimportFrom(methods, ...) plus any classes and methods which areto be exported need to be declared in theNAMESPACE file. Forexample, thestats4 package has

export(mle) # exporting methods implicitly exports the genericimportFrom("stats", approx, optim, pchisq, predict, qchisq, qnorm, spline)## For these, we define methods or (AIC, BIC, nobs) an implicit generic:importFrom("stats", AIC, BIC, coef, confint, logLik, nobs, profile,           update, vcov)exportClasses(mle, profile.mle, summary.mle)## All methods for imported generics:exportMethods(coef, confint, logLik, plot, profile, summary,              show, update, vcov)## implicit generics which do not have any methods hereexport(AIC, BIC, nobs)

All S4 classes to be used outside the package need to be listed in anexportClasses directive. Alternatively, they can be specifiedusingexportClassPattern75 in the same style asforexportPattern. To export methods for generics from otherpackages anexportMethods directive can be used.

Note that exporting methods on a generic in the namespace will alsoexport the generic, and exporting a generic in the namespace will alsoexport its methods. If the generic function is not local to thispackage, either because it was imported as a generic function or becausethe non-generic version has been made generic solely to add S4 methodsto it (as for functions such ascoef in the example above), itcan be declaredvia either or both ofexport orexportMethods, but the latter is clearer (and is used in thestats4 example above). In particular, for primitive functionsthere is no generic function, soexport would export theprimitive, which makes no sense. On the other hand, if the generic islocal to this package, it is more natural to export the function itselfusingexport(), and thismust be done if an implicitgeneric is created without setting any methods for it (as is the caseforAIC instats4).

A non-local generic function is only exported to ensure that calls tothe function will dispatch the methods from this package (and that isnot done or required when the methods are for primitive functions). Forthis reason, you do not need to document such implicitly created genericfunctions, andundoc in packagetools will not report them.

If a package uses S4 classes and methods exported from another package,but does not import the entire namespace of the otherpackage76, it needsto import the classes and methods explicitly, with directives

importClassesFrom(package, ...)importMethodsFrom(package, ...)

listing the classes and functions with methods respectively. Suppose wehad two small packagesA andB withB usingA.Then they could haveNAMESPACE files

export(f1, ng1)exportMethods("[")exportClasses(c1)

and

importFrom(A, ng1)importClassesFrom(A, c1)importMethodsFrom(A, f1)export(f4, f5)exportMethods(f6, "[")exportClasses(c1, c2)

respectively.

Note thatimportMethodsFrom will also import any generics definedin the namespace on those methods.

It is important if you export S4 methods that the corresponding genericsare available. You may for example need to importcoef fromstats to make visible a function to be converted into itsimplicit generic. But it is better practice to make use of the genericsexported bystats4 as this enables multiple packages tounambiguously set methods on those generics.


Next:, Previous:, Up:Creating R packages   [Contents][Index]

1.6 Writing portable packages

This section contains advice on writing packages to be used on multipleplatforms or for distribution (for example to be submitted to a packagerepository such asCRAN).

Portable packages should have simple file names: use only alphanumericASCII characters and period (.), and avoid those namesnot allowed under Windows (seePackage structure).

Many of the graphics devices are platform-specific: evenX11()(akax11()) which although emulated on Windows may not beavailable on a Unix-alike (and is not the preferred screen device on OSX). It is rarely necessary for package code or examples to open a newdevice, but if essential,77 usedev.new().

UseR CMD build to make the release.tar.gz file.

R CMD check provides a basic set of checks, but often furtherproblems emerge when people try to install and use packages submitted toCRAN – many of these involve compiled code. Here are somefurther checks that you can do to make your package more portable.

  • If your package has aconfigure script, provide aconfigure.win orconfigure.ucrt script to be used on Windows (anemptyconfigure.win file if no actions are needed).
  • If your package has aMakevars orMakefile file, make surethat you use only portable make features. Such files should beLF-terminated78 (including the finalline of the file) and not make use of GNU extensions. (The POSIXspecification is available athttps://pubs.opengroup.org/onlinepubs/9699919799/utilities/make.html;anything not documented there should be regarded as an extension to beavoided. Further advice can be found athttps://www.gnu.org/software/autoconf/manual/autoconf.html#Portable-Make. )Commonly misused GNU extensions are conditional inclusions (ifeqand the like),${shell ...},${wildcard ...} andsimilar, and the use of+=79 and:=. Also, the use of$< otherthan in implicit rules is a GNU extension, as is the$^ macro.As is the use of.PHONY (some other makes ignore it).Unfortunately makefiles which use GNU extensions often run on otherplatforms but do not have the intended results.

    Note that the-C flag formake is not included in thePOSIX specification and is not implemented by some of themakes which have been used with R. However, it is morecommonly implemented (e.g. by FreeBSDmake) than the GNU-specific--directory=.

    You should not rely on built-in/defaultmake rules, even whenspecified by POSIX, as somemakes do not have the POSIX onesand others have altered them.

    The use of${shell ...} can be avoided by using backticks, e.g.

    PKG_CPPFLAGS = `gsl-config --cflags`

    which works in all versions ofmake known80 to beused with R.

    If you really must require GNU make, declare it in theDESCRIPTIONfile by

    SystemRequirements: GNU make

    and ensure that you use the value of environment variableMAKE(and not justmake) in your scripts. (On some platforms GNUmake is available under a name such asgmake, and thereSystemRequirements is used to setMAKE.) Yourconfigure script (or similar) does need to check that theexecutable pointed to byMAKE is indeed GNU make.

    If you only need GNU make for parts of the package which are rarelyneeded (for example to create bibliography files undervignettes), use a file calledGNUmakefile rather thanMakefile as GNU make (only) will use the former.

    macOS has used GNU make for many years (it previously used BSD make),but the version has been frozen at 3.81 (from 2006).

    Since the only viable make for Windows is GNU make, it is permissible touse GNU extensions in filesMakevars.win,Makevars.ucrt,Makefile.win orMakefile.ucrt.

  • If you usesrc/Makevars to compile code in a subdirectory,ensure that you have followed all the advice above. In particular
    • Anticipate a parallelmake. SeeUsingMakevars.
    • Pass macros down to the makefile in the subdirectory, includingall the needed compiler flags (including PIC and visibilityflags). If they are used (even by a default rule) in the subdirectory’sMakefile, this includes macros ‘AR’ and ‘RANLIB’.SeeCompiling in sub-directories, which has a C example. A C++example:
      pkg/libpkg.a:        (cd pkg && $(MAKE) -f make_pkg libpkg.a \         CXX="$(CXX)" CXXFLAGS="$(CXXFLAGS) $(CXXPICFLAGS) $(C_VISIBILITY)" \         AR="$(AR)" RANLIB="$(RANLIB)")
    • Ensure that cleanup will be performed byR CMD build, forexample in acleanup script or a ‘clean’ target.
  • If your package uses asrc/Makefile file to compile code to belinked into R, ensure that it uses exactly the same compiler and flagsettings that R uses when compiling such code: people often forget‘PIC’ flags. IfR CMD config is used, this needs somethinglike (for C++)
    RBIN = `"${R_HOME}/bin/R"`CXX = `"${RBIN}" CMD config CXX`CXXFLAGS = `"${RBIN}" CMD config CXXFLAGS` `"${RBIN}" CMD config CXXPICFLAGS`
  • Names of source files including= (such assrc/complex_Sig=gen.c) will confuse somemake programsand should be avoided.
  • Bash extensions also need to be avoided in shell scripts, includingexpressions in Makefiles (which are passed to the shell for processing).Some R platforms use strict81Bourne shells: an earlier R toolset on Windows82 and some Unix-alike OSes useash (https://en.wikipedia.org/wiki/Almquist_shell,a ‘lightweight shell with few builtins) or derivatives such asdash.Beware of assuming that all the POSIX command-line utilities areavailable, especially on Windows where only a subset (which has changedby version ofRtools) is provided for use with R. Oneparticular issue is the use ofecho, for which two behavioursare allowed(https://pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html)and both have occurred as defaults on R platforms: portableapplications should use neither-n (as the first argument) norescape sequences. The recommended replacement forecho -n isthe commandprintf. Another common issue is the construction
    export FOO=value

    which isbash-specific (first set the variable then export itby name).

    Usingtest -e (or[ -e ]) in shell scripts is not fullyportable83:-f is normally what is intended.Flags-a and-o are nowadays declared obsolescent byPOSIX and should not be used. They are easily replaced by more legibleforms: replace

    test A -a Btest A -o B

    by

    test A && test Btest A || test B

    Use of ‘brace expansion’, e.g.,

    rm -f src/*.{o,so,d}

    is not portable.

    The string equality operator in shell tests is= :== isa GNU extension.

    The-o flag forset in shell scripts is optional inPOSIX and not supported on all the platforms R is used on.

    The variable ‘OSTYPE’ is shell-specific and its values arerather unpredictable and may include a version such as‘darwin19.0’:`uname` is often what is intended (withcommon values ‘Darwin’ and ‘Linux’).

    On macOS which shell/bin/sh invokes is user- andplatform-dependent: it might bebash version 3.2,dash orzsh (for new accounts it iszsh,for accounts ported from Mojave or earlier it is usuallybash).

    It is not portable to specifybash as the shell let alone aspecific path such as/bin/bash.

  • R is not built by default as a shared library on non-Windowsplatforms (although it commonly is on macOS to support the GUI), sothere need not be a filelibR.so norlibR.dylib. Users ofcmake orrust have all too frequently assumedotherwise, so do ensure your package is checked under a vanilla R build.SeeConfiguration options inR Installation and Administrationfor more information.
  • Make use of the abilities of your compilers to check thestandards-conformance of your code. For example,gcc,clang andgfortran84 can be used with options-Wall -pedantic to alertyou to potential problems. This is particularly important for C++,whereg++ -Wall -pedantic will alert you to the use of some ofthe GNU extensions which fail to compile on most other C++ compilers. IfR was not configured accordingly, one can achieve thisviapersonalMakevars files.SeeCustomizing package compilation inR Installation and Administrationfor more information.

    Portable C++ code needs to follow all of the 2011, 2014 and 2017standards (including not using deprecated/removed features) or tospecify C+11/14/17/20/23 where available (which is not the case on allR platforms). Currently C++20 support is patchy across Rplatforms.

    If using Fortran with the GNU compiler, use the flags-std=f95-Wall -pedantic which reject most GNU extensions and features fromlater standards. (Although R only requires Fortran 90,gfortran does not have a way to specify that standard.) Alsoconsider-std=f2008 as some recent compilers have Fortran 2008or even 2018 as the minimum supported standard.

    As from macOS 11 (late 2020), its C compiler sets the flag-Werror=implicit-function-declaration by default which forcesstricter conformance to C99. This can be used on other platforms withgcc orclang. If your package has a(autoconf-generated)configure script, tryinstalling it whilst using this flag, and read through theconfig.log file — compilation warnings and errors can lead tofeatures which are present not being detected. (If possible do this onseveral platforms.)

  • R CMD check performs some checks for non-portablecompiler/linker flags insrc/Makevars. However, it cannot checkthe meaning of such flags, and some are commonly accepted but withcompiler-specific meanings. There are other non-portable flags whichare not checked, nor aresrc/Makefile files and makefiles insub-directories. As a comment in the code says

    It is hard to think of anything apart from-I* and-D*that is safe for general use …

    although-pthread is pretty close to portable. (Option-U is portable but little use on the command line as it willonly cancel built-in defines (not portable) and those defined earlier onthe command line (R does not use any).)

    The GNU option-pipe used to be widely accepted byC/C++/Fortran compilers, but was removed inflang-new 18.In any case, it should not be used in distributed code as it may lead toexcessive memory use.

    People have usedconfigure to customizesrc/Makevars,including for specific compilers. This is unsafe for several reasons.First, unintended compilers might meet the check—for example, severalcompilers other than GCC identify themselves as ‘GCC’ whilst being onlypartially conformant. Second, future versions of compilers may behavedifferently (including updates to quite old series) so for example-Werror (and specializations) can make a packagenon-installable under a future version. Third, using flags to suppressdiagnostic messages can hide important information for debugging on aplatform not tested by the package maintainer. (R CMD checkcan optionally report on unsafe flags which were used.)

    Avoid the use of-march and especially-march=native.This allows the compiler to generate code that will only run on aparticular class of CPUs (that of the compiling machine for‘native’). People assume this is a ‘minimum’ CPU specification,but that is not how it is documented forgcc (it is acceptedbyclang but apparently it is undocumented what precisely itdoes, and it can be accepted and may be ignored for other compilers).(For personal use-mtune is safer, but still not portableenough to be used in a public package.) Not evengcc supports‘native’ for all CPUs, and it can do surprising things if it findsa CPU released later than its version.

  • Do be very careful with passing arguments between R, C and Fortrancode. In particular,long in C will be 32-bit on some Rplatforms (including 64-bit Windows), but 64-bit on most modern Unix andLinux platforms. It is rather unlikely that the use oflong in Ccode has been thought through: if you need a longer type thanintyou should use a configure test for a C99/C++11 type such asint_fast64_t (and failing that,long long) and typedefyour own type, or use another suitable type (such assize_t, butbeware that is unsigned andssize_t is not portable).

    It is not safe to assume thatlong and pointer types are the samesize, and they are not on 64-bit Windows. If you need to convertpointers to and from integers use the C99/C++11 integer typesintptr_t anduintptr_t (in the headers<stdint.h>and<cstdint>: they are not required to be implemented by thestandards but are used in C code by R itself).

    Note thatinteger in Fortran corresponds toint in C onall R platforms. There is no such guarantee for Fortranlogical, and recentgfortran maps it toint_least32_t on most platforms.

  • Under no circumstances should your compiled code ever callabortorexit85: these terminate the user’s R process, quite possiblylosing all unsaved work. One usage that could callabort is theassert macro in C or C++ functions, which should never be activein production code. The normal way to ensure that is to define themacroNDEBUG, andR CMD INSTALL does so as part of thecompilation flags. Beware of including headers (including from otherpackages) which could undefine it, now or in future versions. If youwish to useassert during development, you can include-UNDEBUG inPKG_CPPFLAGS or#undef it in yourheaders or code files. Note that your ownsrc/Makefile ormakefiles in sub-directories may also need to defineNDEBUG.

    This applies not only to your own code but to any external software youcompile in or link to.

    Nor should Fortran code callSTOP norEXIT (a GNU extension).

  • Compiled code should not write tostdout orstderr and C++and Fortran I/O should not be used. As with the previous item suchcalls may come from external software and may never be called, butpackage authors are often mistaken about that.
  • Compiled code should not call the system random number generators suchasrand,drand48 andrandom86, but rather use theinterfaces to R’s RNGs described inRandom number generation. Inparticular, if more than one package initializes a system RNG (e.g.viasrand), they will interfere with each other. Thisapplies also to Fortran 90’srandom_number andrandom_seed, and Fortran 2018’srandom_init. And to GNUFortran’srand,irand andsrand. Except fordrand48, what PRNG these functions use isimplementation-dependent.

    Nor should the C++11 random number library be used nor any otherthird-party random number generators such as those in GSL.

  • Use ofsprintf andvsprintf is regarded as a potentialsecurity risk and warned about on some platforms.87R CMD check reports if any callsare found.
  • Errors in memory allocation and reading/writing outside arrays are verycommon causes of crashes (e.g., segfaults) on some machines.SeeChecking memory access for tools which can be used to look for this.
  • Many platforms will allow unsatisfied entry points in compiled code, butwill crash the application (here R) if they are ever used. Some(notably Windows) will not. Looking at the output of
    nm -pg mypkg.so

    and checking if any of the symbols markedU is unexpected is agood way to avoid this.

  • Linkers have a lot of freedom in how to resolve entry points indynamically-loaded code, so the results may differ by platform. Onearea that has caused grief is packages including copies of standardsystem software such aslibz (especially those already linkedinto R). In the case in point, entry pointgzgets wassometimes resolved against the old version compiled into the package,sometimes against the copy compiled into R and sometimes against thesystem dynamic library. The only safe solution is to rename the entrypoints in the copy in the package. We have even seen problems withentry point namemyprintf, which is a system entrypoint88 on some Linux systems.

    A related issue is the naming of libraries built as part of the packageinstallation. macOS and Windows have case-insensitive file systems, sousing

    -L. -lLZ4

    inPKG_LIBS will matchliblz4. And-L. onlyappends to the list of searched locations, andliblz4 might befound in an earlier-searched location (and has been). The only safe wayis to give an explicit path, for example

    ./libLZ4.a
  • Conflicts between symbols in DLLs are handled in very platform-specificways. Good ways to avoid trouble are to make as many symbols aspossible static (check withnm -pg), and to use names which areclearly tied to your package (which also helps users if anything does gowrong). Note that symbol names starting withR_ are regarded aspart of R’s namespace and should not be used in packages.
  • It is good practice for DLLs to register their symbols(seeRegistering native routines), restrict visibility(seeControlling visibility) and not allow symbol search(seeRegistering native routines). It should be possible for a DLLto have only one visible symbol,R_init_pkgname, onsuitable platforms89,which would completely avoid symbol conflicts.
  • It is not portable to call compiled code in R or other packagesvia.Internal,.C,.Fortran,.Call or.External, since such interfaces are subject to change withoutnotice and will probably result in your code terminating the Rprocess.
  • Do not use (hard or symbolic) file links in your package sources.Where possibleR CMD build will replace them by copies.
  • If you do not yourself have a Windows system, consider submitting yoursource package to WinBuilder (https://win-builder.r-project.org/)before distribution. If you need to check on an M1 Mac, there is acheck service athttps://mac.r-project.org/macbuilder/submit.html.
  • It is bad practice for package code to alter the search path usinglibrary,require orattach and this often does notwork as intended. For alternatives, seeSuggested packages andwith().
  • Examples can be run interactivelyviaexample as well asin batch mode when checking. So they should behave appropriately inboth scenarios, conditioning byinteractive() the parts whichneed an operator or observer. For instance, progressbars90 are only appropriate ininteractive use, as is displaying help pages or callingView()(see below).
  • Be careful with the order of entries in macros such asPKG_LIBS.Some linkers will re-order the entries, and behaviour can differ betweendynamic and static libraries. Generally-L options shouldprecede91 the libraries (typicallyspecified by-l options) to be found from those directories,and libraries are searched once in the order they are specified. Notall linkers allow a space after-L .
  • Care is needed with the use ofLinkingTo. This puts one or moredirectories on the include search path ahead of system headers but(prior to R 3.4.0) after those specified in theCPPFLAGS macroof the R build (which normally includes-I/usr/local/include,but most platforms ignore that and include it with the system headers).

    Any confusion would be avoided by havingLinkingTo headers in adirectory named after the package. In any case, name conflicts ofheaders and directories under packageinclude directories shouldbe avoided, both between packages and between a package and system andthird-party software.

  • Thear utility is often used in makefiles to make staticlibraries. Its modifieru is defined by POSIX but is disabled inGNUar on some Linux distributions which use‘deterministic mode’. The safest way to make a static library is to firstremove any existing file of that name then use$(AR) -cr and then$(RANLIB) if needed (which is system-dependent: on mostsystems92ar alwaysmaintains a symbol table). The POSIX standard says options should bepreceded by a hyphen (as in-cr), although most OSes acceptthem without.Note that on some systemsar -cr must have at least one filespecified.

    Thes modifier (to replace a separate call toranlib)is required by X/OPEN but not POSIX, soar -crs is notportable.

    For portability theAR andRANLIB macros should always beused – some builds require wrappers such asgcc-ar or extraarguments to specify plugins.

  • Thestrip utility is platform-specific (andCRANprohibits removing debug symbols). For example the options--strip-debug and--strip-unneeded of the GNU versionare not supported on macOS: the POSIX standard forstripdoes not mention any options, and what calling it without options doesis platform-dependent. Stripping a.so file could even preventit being dynamically loaded into R on an untested platform.

    ld -S invokesstrip --strip-debug for GNUld (and similarly on macOS) but is not portable: in particularon Solaris it did something completely different and took an argument.

  • Some people have a need to set a locale. Locale names are not portable,and e.g. ‘fr_FR.utf8’ is commonly used on Linux but not acceptedon macOS. ‘fr_FR.UTF-8’ is more portable, being accepted on recentLinux,AIX, FreeBSD, macOS and Solaris (at least). However, some Linuxdistributions micro-package, so locales defined byglibc(including these examples) may not be installed.
  • Avoid spaces in file names, not least as they can cause difficulties forexternal tools. An example was a package with aknitrvignette that used spaces in plot names: this caused some older versionsofpandoc to fail with a baffling error message.

    Non-ASCII filenames can also cause problems (particularly in non-UTF-8locales).

  • Take care in naming LaTeX macros (also known as ‘commands’) invignette sources: if these are also defined in a future version of oneof the LaTeX packages used there will be a fatal error. One instancein 2021 was package ‘hyperref’ newly defining ‘\C’, ‘\F’,‘\G’, ‘\U’ and ‘\textapprox’. If you are confident thatyour definitions will be the only ones relevant you can use‘\renewcommand’ but it is better to use names clearly associatedwith your package.
  • Make sure that any version requirement for Java code is both declared inthe ‘SystemRequirements’ field93 and tested atruntime (not least as the Java installation when the package isinstalled might not be the same as when the package is run and will notbe for binary packages).

    When specifying a minimum Java version please use the official versionnames, which are (confusingly)

    1.1 1.2 1.3 1.4 5.0 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

    and as from 2018 a year.month scheme such as ‘18.9’ is also inuse. Fortunately only the integer values are likely to be relevant.If at all possible, use one of theLTS versions (8, 11, 17, 21 …)as the minimum version. The preferred form of version specification is

    A suitable test for Java at least version 8 for packages usingrJava would be something like

    .jinit()jv <- .jcall("java/lang/System", "S", "getProperty", "java.runtime.version")if(substr(jv, 1L, 2L) == "1.") {  jvn <- as.numeric(paste0(strsplit(jv, "[.]")[[1L]][1:2], collapse = "."))  if(jvn < 1.8) stop("Java >= 8 is needed for this package but not available")}

    Java 9 changed the format of this string (which used to be somethinglike ‘1.8.0_292-b10’); Java 11 gavejv as ‘11+28’whereas Java 11.0.11 gave ‘11.0.11+9’.(https://openjdk.org:443/jeps/322 details the current scheme.Note that it is necessary to allow for pre-releases like‘11-ea+22’.)

    Note too that the compiler used to produce ajar can impose a minimumJava version, often resulting in an arcane message like

    java.lang.UnsupportedClassVersionError: ... Unsupported major.minor version 52.0

    (Wherehttps://en.wikipedia.org/wiki/Java_class_file mapsclass-file version numbers to Java versions.) Compile with somethinglikejavac -target 11 to ensure this is avoided. Note thisalso applies to packages distributing (or even downloading) compiledJava code produced by others, so their requirements need to be checked(they are often not documented accurately) and accounted for. It shouldbe possible to check the class-file versionvia command-lineutilityjavap, if necessary after extracting the.classfiles from a.jar archive. For example,

    jar xvf some.jarjavap -verbose path/to/some.class | grep major

    Some packages have stated a requirement on a particularJDK, but apackage should only be requiring aJRE unless providing its own Javainterface.

    Java 8 is still in widespread use (and may remain so because of licencechanges and support on older OSes: OpenJDK has security support untilMarch 2026). On the other hand, newer platforms may only have supportfor recent versions of Java: for ‘arm64’ macOS the firstofficially supported version was 17.

  • A package with a hard-to-satisfy system requirement is by definition notportable, annoyingly so if this is not declared in the‘SystemRequirements’ field. The most common example is the use ofpandoc, which is only available for a very limited range ofplatforms (and has onerous requirements to install from source) and hascapabilities94 that vary by build but are not documented. Several recentversions ofpandoc for macOS did not work on R’s thentarget of High Sierra (and this too was undocumented). Another exampleis the Rust compilation system (cargo andrustc).

    Usage of external commands should always be conditional on a test forpresence (perhaps usingSys.which), as well as declared in the‘SystemRequirements’ field. A package should pass its checkswithout warnings nor errors without the external command being present.

    An external command can be a (possibly optional) requirement for animported or suggested package but needed for examples, tests orvignettes in the package itself. Such usages should always be declaredand conditional.

    Interpreters for scripting languages such as Perl, Python and Ruby needto be declared as system requirements and used conditionally: forexample macOS 10.16 was announced not to have them (but released asmacOS 11 with them); later it was announced that macOS 12.3 does nothave Python 2 and only a minimal install of Python 3 is included.Python 2 has passed end-of-life and been removed from many majordistributions. Support for Rust or Go cannot be assumed.

    Commandcmake is not commonly installed, and where it is, itmight not be on the path. In particular, the most common location onmacOS is/Applications/CMake.app/Contents/bin/cmake and thatshould be looked for ifcmake is not found on the path.

  • Be sure to use portable encoding names: none ofutf8,macandmacroman is portable. See the help forfile for moredetails.
  • Do not invoke R by plainR,Rscript or (onWindows)Rterm in your examples, tests, vignettes, makefilesor other scripts. As pointed out in several places earlier in thismanual, use something like
    "$(R_HOME)/bin/Rscript""$(R_HOME)/bin$(R_ARCH_BIN)/Rterm"

    with appropriate quotes (as, although not recommended,R_HOME cancontain spaces).

  • Do not useR_HOME in makefiles except when passing them to the shell.Specifically, do not useR_HOME in the argument toinclude,asR_HOME can contain spaces. Quoting the argument toincludedoes not help. A portable and the recommended way to avoid the problem of spaces in${R_HOME} is using option-f ofmake. This iseasy to do with recursive invocation ofmake, which is also theonly usual situation whenR_HOME is needed in the argument forinclude.
    $(MAKE) -f "${R_HOME}/etc${R_ARCH}/Makeconf" -f Makefile.inner
  • If distributing datasets involving date-times, consider if a time zoneneeds to be specified. The most portable way to distribute date-times isas objects of class"POSIXct" and as these record the time inUTC, the time represented is independent of the time zone: but how it isprinted may not be. Objects of class"POSIXlt" should have a"tzone" attribute. Dates (e.g, birthdays) are conventionallyconsidered independently of time zone.

    If input of date-times involves words not just numbers (day and monthnames, the am/pm indicator) consider if the local categoryLC_TIME needs to be set. The am/pm indicator in the C/POSIXlocale isAM/PM, but this need not be the case in other Englishlocales. Worse, the OS has been known to change this at an update.This applies also to testing output.

    Day and month names (and especially their abbreviations) in non-Englishlanguages may differ between OSes.

  • If at all possible avoid any Internet access during packageinstallation. Installation and use may well be on differentmachines/accounts and those allowed to install software may have noInternet access, and being self-contained helps ensure long-termreproducibility.

Do be careful in what your tests (and examples) actually test. Badpractice seen in distributed packages include:

  • It is not reasonable to test the time taken by a command: you cannotknow how fast or how heavily loaded an R platform might be. At bestyou can test a ratio of times, and even that is fraught withdifficulties and not advisable: for example, the garbage collector maytrigger at unpredictable times following heuristics that may changewithout notice.
  • Do not test the exact format of R messages (from R itself or fromother packages): They change, and they can be translated.

    Packages have even tested the exact format of system error messages,which are platform-dependent and perhaps locale-dependent. For example,in late 2021libcurl changed its warning/error messages,including when URLs are not found.

  • Do not test for the absence of warnings (something users oftestthat are fond of). Future changes in either R orpackages you make use of can create new warnings, and your tests shouldnot make these into errors. (Some deprecation notices may be intendedto remain as warnings for a long time.)
  • If you use functions such asView, remember that in testing thereis no one to look at the output. It is better to use something like one of
    if(interactive()) View(obj) else print(head(obj))if(interactive()) View(obj) else str(obj)
  • Be careful when comparing file paths. There can be multiple paths to asingle file, and some of these can be very long character strings. Ifpossible canonicalize paths before comparisons, but study?normalizePath to be aware of the pitfalls.
  • Only test the accuracy of results if you have done a formal erroranalysis. Things such as checking that probabilities numerically sum toone are silly: numerical tests should always have a tolerance. That thetests on your platform achieve a particular tolerance says little aboutother platforms. R is configured by default to make use of longdoubles where available, but they may not be available or be too slowfor routine use. Most R platforms use ‘ix86’ or‘x86_64’ CPUs: these may use extended precision registers onsome but not all of theirFPU instructions. Thus the achieved precisioncan depend on the compiler version and optimization flags—ourexperience is that 32-bit builds tend to be less precise than 64-bitones. But not all platforms use those CPUs, and not all95 which use them configure them to allow the use of extendedprecision. In particular, current ARM CPUs do not have extendedprecision nor long doubles, andclang currently has longdouble the same as double on all ARM CPUs. On the other hand some CPUshave higher-precision modes which may be used forlong double,notably 64-bit PowerPC and Sparc.

    If you must try to establish a tolerance empirically, configure andbuild R with--disable-long-double and use appropriatecompiler flags (such as-ffloat-store and-fexcess-precision=standard forgcc, depending on theCPU type96) tomitigate the effects of extended-precision calculations. The platformmost often seen to give different numerical results is ‘arm64’ macOS,so be sure to include that in any empirical determination.

    Tests which involve random inputs or non-deterministic algorithms shouldnormally set a seed or be tested for many seeds.

  • Tests should useoptions(warn = 1) as reporting
    There were 22 warnings (use warnings() to see them)

    is pointless, especially for automated checking systems.

  • If your package uses dates/times, ensure that it works in all timezones,especially those near boundaries (problems have most often be seen in‘Europe/London’ (zero offset in Winter) and‘Pacific/Auckland’, near enough the International Date line) andwith offsets not in whole hours (Adelaide, Chatham Islands, …).More extreme examples are ‘Africa/Conakry’ (permanent UTC),‘Asia/Calcutta’ (no DST, permanent half-hour offset)and ‘Pacific/Kiritimati’(no DST, more than 12 hours ahead of UTC).

Next:, Up:Writing portable packages   [Contents][Index]

1.6.1 PDF size

There are a several tools available to reduce the size of PDF files:often the size can be reduced substantially with no or minimal loss inquality. Not only do large files take up space: they can stress the PDFviewer and take many minutes to print (if they can be printed at all).

qpdf (https://qpdf.sourceforge.io/) can compresslosslessly. It is fairly readily available (e.g. it is included inrtools, has packages in Debian/Ubuntu/Fedora, and isinstalled as part of theCRAN macOS distribution of R).R CMD build has an option to runqpdf over PDF filesunderinst/doc and replace them if at least 10Kb and 10% issaved. The full path to theqpdf command can be supplied asenvironment variableR_QPDF (and is on theCRAN binaryof R for macOS). It seems MiKTeX does not use PDF objectcompression and soqpdf can reduce considerably the sizes offiles it outputs: MiKTeX’s defaults can be overridden by code in thepreamble of an Sweave or LaTeX file — see how this is done for theR reference manual athttps://svn.r-project.org/R/trunk/doc/manual/refman.top.

Other tools can reduce the size of PDFs containing bitmap images atexcessively high resolution. These are often best re-generated (forexampleSweave defaults to 300 ppi, and 100–150 is moreappropriate for a package manual). These tools include Adobe Acrobat(not Reader), Apple’s Preview97 and Ghostscript (whichconverts PDF to PDF by

ps2pdfoptions -dAutoRotatePages=/None -dPrinted=falsein.pdfout.pdf

and suitable options might be

-dPDFSETTINGS=/ebook-dPDFSETTINGS=/screen

Seehttps://ghostscript.readthedocs.io/en/latest/VectorDevices.html formore such and consider all the options for image downsampling). Therehave been examples inCRAN packages for which current versionsof Ghostscript produced much bigger reductions than earlier ones (e.g.at the upgrades from9.50 to9.52, from9.55 to9.56 and then to10.00.0).

We come across occasionally large PDF files containing excessivelycomplicated figures using PDF vector graphics: such figures are oftenbest redesigned or failing that, output as PNG files.

Option--compact-vignettes toR CMD build defaults tovalue ‘qpdf’: use ‘both’ to try harder to reduce the size,provided you have Ghostscript available (see the help fortools::compactPDF).


Next:, Previous:, Up:Writing portable packages   [Contents][Index]

1.6.2 Check timing

There are several ways to find out where time is being spent in thecheck process. Start by setting the environment variable_R_CHECK_TIMINGS_ to ‘0’. This will report the total CPUtimes (not Windows) and elapsed times for installation and several checks,including for running examples, tests and vignettes, under each sub-architecture ifappropriate. For tests and vignettes, it reports the time for each aswell as the total.

Setting_R_CHECK_TIMINGS_ to a positive value sets a threshold (inseconds elapsed time) for reporting timings.

If you need to look in more detail at the timings for examples, useoption--timings toR CMD check (this is set by--as-cran). This adds a summary to the check output for allthe examples with CPU or elapsed time of more than 5 seconds. Itproduces a filemypkg.Rcheck/mypkg-Ex.timingscontaining timings for each help file: it is a tab-delimited file whichcan be read into R for further analysis.

Timings for the tests and vignette runs are given at the bottom of thecorresponding log file: note that log files for successful vignette runsare only retained if environment variable_R_CHECK_ALWAYS_LOG_VIGNETTE_OUTPUT_ is set to a true value.


Next:, Previous:, Up:Writing portable packages   [Contents][Index]

1.6.3 Encoding issues

The issues in this subsection have been much alleviated by the change inR 4.2.0 to running the Windows port of R in a UTF-8 locale whereavailable. However, Windows users might be running an earlier versionof R on an earlier version of Windows which does not support UTF-8locales.

Care is needed if your package contains non-ASCII text, and inparticular if it is intended to be used in more than one locale. It ispossible to mark the encoding used in theDESCRIPTION file and in.Rd files, as discussed elsewhere in this manual.

First, consider carefully if you really need non-ASCII text.Some users of R will only be able to view correctly text in theirnative language group (e.g. Western European, Eastern European,Simplified Chinese) andASCII.98. Other characters may not be rendered at all,rendered incorrectly, or cause your R code to give an error. For.Rd documentation, marking the encoding and includingASCII transliterations is likely to do a reasonable job. Theset of characters which is commonly supported is wider than it used tobe around 2000, but non-Latin alphabets (Greek, Russian, Georgian,…) are still often problematic and those with double-widthcharacters (Chinese, Japanese, Korean, emoji) often need specialistfonts to render correctly.

SeveralCRAN packages have messages in their R code in French (and afew in German). A better way to tackle this is to use theinternationalization facilities discussed elsewhere in this manual.

FunctionshowNonASCIIfile in packagetools can help infinding non-ASCII bytes in files.

There is a portable way to have arbitrary text in character strings(only) in your R code, which is to supply them in Unicode as‘\uxxxx’ escapes (or, rarely needed except for emojis,‘\Uxxxxxxxx’ escapes). If there are any characters not in thecurrent encoding the parser will encode the character string as UTF-8and mark it as such. This applies also to character strings indatasets: they can be prepared using ‘\uxxxx’ escapes or encoded inUTF-8 in a UTF-8 locale, or even converted to UTF-8viaiconv(). If you do this, make sure you have ‘R (>= 2.10)’(or later) in the ‘Depends’ field of theDESCRIPTION file.

R sessions running in non-UTF-8 locales will if possible re-encodesuch strings for display (and this is done byRGui on olderversions of Windows, for example). Suitable fonts will need to beselected or made available99 both for the console/terminal and graphics devicessuch as ‘X11()’ and ‘windows()’. Using ‘postscript’ or‘pdf’ will choose a default 8-bit encoding depending on thelanguage of the UTF-8 locale, and your users would need to be told howto select the ‘encoding’ argument.

Note that the previous two paragraphs only apply to character strings inR code. Non-ASCII characters are particularly prevalent in comments(in the R code of the package, in examples, tests, vignettes and evenin theNAMESPACE file) but should be avoided there. Most commonlypeople use the Windows extensions to Latin-1 (often directional singleand double quotes, ellipsis, bullet and en and em dashes) which are notsupported in strict Latin-1 locales nor in CJK locales on Windows. Asurprisingly common misuse is to use a right quote in ‘don't’instead of the correct apostrophe.

Datasets can include marked UTF-8 or Latin-1 character strings. As Ris nowadays unlikely to be run in a Latin-1 or Windows’ CP1252 locale,for performance reasons these should be converted to UTF-8.

If you want to runR CMD check on a Unix-alike over a packagethat sets a package encoding in itsDESCRIPTION fileand donot use a UTF-8 locale you may need to specify a suitable localevia environment variableR_ENCODING_LOCALES. The defaultis equivalent to the value

"latin1=en_US:latin2=pl_PL:UTF-8=en_US.UTF-8:latin9=fr_FR.iso885915@euro"

(which is appropriate for a system based onglibc: macOS requireslatin9=fr_FR.ISO8859-15) except that if the current locale isUTF-8 then the package code is translated to UTF-8 for syntax checking,so it is strongly recommended to check in a UTF-8 locale.


Next:, Previous:, Up:Writing portable packages   [Contents][Index]

1.6.4 Portable C and C++ code

Writing portable C and C++ code is mainly a matter of observing thestandards (C99, C++14 or where declared C++11/17/20) and testing thatextensions (such as POSIX functions) are supported. Do make maximal useof your compiler diagnostics — this typically means using flags-Wall and-pedantic for both C and C++ and additionally-Werror=implicit-function-declaration and-Wstrict-prototypes for C (on some platforms and compilerversions) these are part of-Wall or-pedantic).

C++ standards: From version 4.0.0 R required and defaultedto C++11; from R 4.1.0 in defaulted to C++14 and from R 4.3.0 toC++17 (where available). For maximal portability a package shouldeither specify a standard (seeUsing C++ code) or be tested underall of C++11, C++14 and C++17.

Later C++ standards, notably C++17 remove features deprecated in earlierversions. Unfortunately some compilers, notablyg++ haveretained these features so if possible test under another compiler (suchas that used on macOS).

Note that the ‘TR1’ C++ extensions are not part of any of thesestandards and the<tr1/name> headers are not supplied by some ofthe compilers used for R, including on macOS. (Use the C++11versions instead.)

A common error is to assume recent versions of compilers or OSes. Inproduction environments ‘long term support’ versions of OSes may be inuse for many years,100 and their compilers may notbe updated during that time. For example, GCC 4.8 was still in use in2022 and could be (in RHEL 7) until 2028: that supports neither C++14nor C++17.

The POSIX standards only require recently-defined functions to bedeclared if certain macros are defined with large enough values, and onsome compiler/OS combinations101 they are not declared otherwise. So you mayneed to include something like one of

#define _XOPEN_SOURCE 600

or

#ifdef __GLIBC__# define _POSIX_C_SOURCE 200809L#endif

beforeany headers. (strdup,strncasecmp andstrnlen are such functions – there were several older platformswhich did not have the POSIX 2008 functionstrnlen.)

‘Linux’ is not a well-defined operating system: it is a kernel plus acollection of components. Most distributions useglibc toprovide most of the C headers and run-time library, but others, notablyAlpine Linux, use other implementations such asmusl — seehttps://wiki.musl-libc.org/functional-differences-from-glibc.html.

However, some common errors are worth pointing out here. It can behelpful to look up functions athttps://cplusplus.com/reference/ orhttps://en.cppreference.com/w/ and compare what is defined in thevarious standards.

More care is needed for functions such asmallinfo which are notspecified by any of these standards—hopefully theman pageon your system will tell you so. Searching online for such pages forvarious OSes (preferably at least Linux and macOS, and the FreeBSDmanual pages athttps://man.freebsd.org/cgi/man.cgi allow you toselect many OSes) should reveal useful information but aconfigure script is likely to be needed to check availability andfunctionality.

Both the compiler and OS (via system header files, which maydiffer by architecture even for nominally the same OS) affect thecompilability of C/C++ code. Compilers from the GCC, LLVM(clang andflang) Intel and Oracle Developer Studiosuites have been used with R, and both LLVMclang andOracle have more than one implementation of C++ headers and library.The range of possibilities makes comprehensive empirical checkingimpossible, and regrettably compilers are patchy at best on warningabout non-standard code.

Some additional information for C++ is available athttps://journal.r-project.org/archive/2011-2/RJournal_2011-2_Plummer.pdfby Martyn Plummer.

Several OSes have or currently do provide multiple C++ runtimes —Solaris did and the LLVMclang compiler has a native C++runtime librarylibc++ but is also used with GCC’slibstdc++ (by default on Debian/Ubuntu/Fedora). This makes itunsafe to assume that OS libraries with a C++ interface are compatiblewith the C++ compiler specified by R. Many of these system librariesalso have C interfaces which should be used in preference to their C++interface. Otherwise it is essential that a package checkscompatibility in itsconfigure script, including that C++ codeusing the library can both be linkedand loaded.


1.6.4.1 Common symbols

Most OSes (including all those commonly used for R) have the conceptof ‘tentative definitions’ where global C variables are defined withoutan initializer. Traditionally the linker resolved all tentativedefinitions of the same variable in different object files to the sameobject, or to a non-tentative definition. However,gcc 10112 andLLVMclang 11113changed their default so that tentative definitions cannot bemerged and the linker will give an error if the same variable is definedin more than one object file. To avoid this, all but one of the Csource files should declare the variableextern — which meansthat any such variables included in header files need to be declaredextern. A commonly used idiom (including by R itself) is todefine all global variables asextern in a header, sayglobals.h (and nowhere else), and then in one (and one only)source file use

#define extern# include "globals.h"#undef extern

A cleaner approach is not to have global variables at all, but to placein a single file common variables (declaredstatic) followed byall the functions which make use of them: this may result in moreefficient code.

The ‘modern’ behaviour can be seen114 by usingcompiler flag-fno-common as part of ‘CFLAGS’ in earlierversions ofgcc andclang.

-fno-common is said to be particularly beneficial for ARM CPUs.

This is not pertinent to C++ which does not permit tentative definitions.


1.6.4.2 C++17 issues

R 4.3.0 and later default to C++17 when compiling C++, and thatfinally removed many C++98 features which were deprecated as long ago asC++11. Compiler/runtime authors have been slow to remove these, butLLVMclang with itslibc++ runtime library finallystarted to do so in 2023 – some others warn but some do not.

The principal offender is the ‘Boost’ collection of C++ headers andlibraries. There are two little-documented ways to work around aspectsof its outdated code. One is to add

-D_HAS_AUTO_PTR_ETC=0

toPKG_CPPLAGS insrc/Makevars,src/Makevars.winandsrc/Makevars.ucrt. This coversthe removal of

std::auto_ptrstd::unary_functionstd::binary_functionstd::random_shufflestd::binder1ststd::binder2nd

with most issues seen with code that includesboost/functional.hpp,usually indirectly.

A rarer issue is the use of illegal values forenum types,usually negative ones such as

BOOST_MPL_AUX_STATIC_CAST(AUX_WRAPPER_VALUE_TYPE, (value - 1));

inboost/mpl/aux_/integral_wrapper.hpp. Adding

 -Wno-error=enum-constexpr-conversion

toPKG_CXXFLAGS will allow this, but that flag is only acceptedby recent versions of LLVMclang (and will not be in future)so needs aconfigure test.

Pre-built versions of currentclang/libc++ areusually available fromhttps://github.com/llvm/llvm-project/releases for a wide range ofplatforms (but the Windows builds there are not compatible withRtools and the macOS ones are unsigned). To selectlibc++ add-stdlib=libc++ toCXX, for exampleby having

CXX="/path/to/clang/clang++ -std=gnu++17 -stdlib=libc++"

in~/.R/Makevars.

Another build for Windows which may be sufficiently compatible withRtools can be found athttps://github.com/mstorsjo/llvm-mingw: this useslibc++.


1.6.4.3 C23 changes

The C23 standard was finally published in Oct 2024, by which time it hadbeen widely implemented for a least a couple of years. It will becomethe default of GCC 15, and R will default to it if available fromR 4.5.0.

Some of the more significant changes are

  • bool,true andfalse become keywords and so can nolonger be used as identifiers.

    These have been available as a boolean type since C99 by including theheaderstdbool.h. Both that and C23115 set the macro__bool_true_false_are_defined to1 so this type can beused in all versions of C supported by R.

  • The meaning of an empty argument list has been changed to mean zeroarguments — however for clarityfun(void) is still preferred bymany code readers and supported by all C standards. (Compilers may warnabout an empty argument list in C23 mode.)
  • INIINITY andNAN are available viaheaderfloat.h and deprecated inmath.h.
  • POSIX functionsmemccpy,strdup andstrndup arepart of C23.
  • There are decimal floating-point types and functions and extendedsupport of binary floating-point functions, including binaryfloating-point constants.

Next:, Previous:, Up:Writing portable packages   [Contents][Index]

1.6.5 Portable Fortran code

For many years almost all known R platforms usedgfortranas their Fortran compiler, but now there are LLVM and ‘classic’flang and the Intel compilersifort116 andifx are nowfree-of-change.

There is still a lot of Fortran code inCRAN packages whichpredates Fortran 77. Modern Fortran compilers are being written totarget a minimum standard of Fortran 2018. and it is desirable thatFortran code in packages complies with that standard. Forgfortran this can be checked by adding-std=f2018 toFFLAGS. The most commonly seen issues are

Unfortunately this flags extensions such asDOUBLE COMPLEX andCOMPLEX*16. R has tested thatDOUBLE COMPLEX works andso is preferred toCOMPLEX*16. (One can also use something likeCOMPLEX(KIND=KIND(0.0D0)).)

GNU Fortran 10 and later give a compilation error for the previouslywidespread practice of passing a Fortran array element where an array isexpected, or a scalar instead of a length-one array. Seehttps://gcc.gnu.org/gcc-10/porting_to.html. As do the IntelFortran compilers, and they can be stricter.

The use ofIMPLICIT NONE is highly recommended – Intel compilerswith-warn will warn on variables without an explicit type.

Common non-portable constructions include

  • The use of Fortran types such asREAL(KIND=8) is very far fromportable. According to the standards this merely enumerates differentsupported types, soDOUBLE PRECISION might beREAL(KIND=3)(and is on an actual compiler). Even if for a particular compiler thevalue indicates the size in bytes, which values are supported isplatform-specific — for examplegfortran supports values of 4and 8 on all current platforms and 10 and 16 on a few (but not forexample on all ‘arm’ CPUs).

    The same applies toINTEGER(KIND=4) andCOMPLEX(KIND=16).

    Many uses of integer and real variable in Fortran code in packages willinterwork with C (for example.Fortran is written in C), and Rhas checked thatINTEGER andDOUBLE PRECISION correspond tothe C typesint anddouble. To make this explicit, fromFortran 2003 one can use the named constantsc_int,c_double andc_double_complex from moduleiso_c_binding.

  • The Intel compilers only recognize the extensions.f (fixed-form)and.f90 (free-form) and not.f95.R CMD INSTALLworks around this for packages without asrc/Makefile.
  • Use of extensions.F and.F90 to indicate source code tobe preprocessed: the preprocessor used is compiler-specific and may ormay not becpp. Compilers may even preprocess files withextension.f or.f90 (Intel does).
  • Fixed form Fortran (with extension.f) should only use 72columns, and free-form at most 132 columns. This includes trailingcomments. Over-long lines may be silently truncated or give a warning.
  • Tabs are not part of the Fortran character set: compilers tend to acceptthem but how they are interpreted is compiler-specific.
  • Fortran-66-style Hollerith constants.

As well as ‘deleted features’, Fortran standards have ‘obsolescentfeatures’. These are similar to ‘deprecated’ in other languages, butthe Fortran standards committee has said it will only move them to‘deleted’ status when they are no longer much used. These include

  • ENTRY statements.
  • FORALL statements.
  • LabelledDO statements.
  • COMMON andEQUIVALENCE statements, andBLOCK DATAunits.
  • ComputedGOTO statements, replaced bySELECT CASE.
  • Statement functions.
  • DATA statements after executable statements.
  • Specific (rather than generic) names for intrinsic functions.

gfortran with option-std=f2018 will warn about these:R will report only in the installation log.


Previous:, Up:Writing portable packages   [Contents][Index]

1.6.6 Binary distribution

If you want to distribute a binary version of a package on Windows ormacOS, there are further checks you need to do to check it is portable:it is all too easy to depend on external software on your own machinethat other users will not have.

For Windows, check what other DLLs your package’s DLL depends on(‘imports’ from in the DLL tools’ parlance). A convenient GUI-basedtool to do so is ‘Dependency Walker’(https://www.dependencywalker.com/) for both 32-bit and 64-bitDLLs – note that this will report as missing links to R’s own DLLssuch asR.dll andRblas.dll. The command-line toolobjdump in the appropriate toolchain will also reveal whatDLLs are imported from. If you use a toolchain other than one providedby the R developers or use your own makefiles, watch out inparticular for dependencies on the toolchain’s runtime DLLs such aslibgfortran,libstdc++ andlibgcc_s.

For macOS, usingR CMD otool -L on the package’s shared object(s)in thelibs directory will show what they depend on: watch forany dependencies in/usr/local/lib or/usr/local/gfortran/lib, notablylibgfortran.?.dylib andlibquadmath.0.dylib.(For ways to fix these,seeBuilding binary packages inR Installation and Administration.)

Many people (including theCRAN package repository) will notaccept source packages containing binary files as the latter are asecurity risk. If you want to distribute a source package which needsexternal software on Windows or macOS, options include

Be aware that license requirements may require you to supply thesources for the additional components (and will if your package has aGPL-like license).


Next:, Previous:, Up:Creating R packages   [Contents][Index]

1.7 Diagnostic messages

Diagnostic messages can be made available for translation, so it isimportant to write them in a consistent style. Using the toolsdescribed in the next section to extract all the messages can give auseful overview of your consistency (or lack of it).Some guidelines follow.


Next:, Previous:, Up:Creating R packages   [Contents][Index]

1.8 Internationalization

There are mechanisms to translate the R- and C-level error and warningmessages. There are only available if R is compiled withNLS support(which is requested byconfigure option--enable-nls,the default).

The procedures make use ofmsgfmt andxgettext which arepart ofGNUgettext and this will need to be installed:‘x86_64’ Windows users can find pre-compiled binaries athttps://www.stats.ox.ac.uk/pub/Rtools/goodies/gettext-tools.zip.


Next:, Up:Internationalization   [Contents][Index]

1.8.1 C-level messages

The process of enabling translations is

  • In a header file that will be included in all the C (or C++ or ObjectiveC/C++) files containing messages that should be translated, declare
    #include <R.h>  /* to include Rconfig.h */#ifdef ENABLE_NLS#include <libintl.h>#define _(String) dgettext ("pkg", String)/* replacepkg as appropriate */#else#define _(String) (String)#endif
  • For each message that should be translated, wrap it in_(...),for example
    error(_("'ord' must be a positive integer"));

    If you want to use different messages for singular and plural forms, youneed to add

    #ifndef ENABLE_NLS#define dngettext(pkg, String, StringP, N) (N == 1 ? String : StringP)#endif

    and mark strings by

    dngettext("pkg",<singular string>,<plural string>, n)
  • In the package’ssrc directory run
    xgettext --keyword=_ -opkg.pot *.c

The filesrc/pkg.pot is the template file, andconventionally this is shipped aspo/pkg.pot.


Next:, Previous:, Up:Internationalization   [Contents][Index]

1.8.2 R messages

Mechanisms are also available to support the automatic translation ofRstop,warning andmessage messages. They makeuse of message catalogs in the same way as C-level messages, but usingdomainR-pkg rather thanpkg. Translation ofcharacter strings insidestop,warning andmessagecalls is automatically enabled, as well as other messages enclosed incalls togettext orgettextf. (To suppress this, useargumentdomain=NA.)

Tools to prepare theR-pkg.pot file are provided in packagetools:xgettext2pot will prepare a file from all stringsoccurring insidegettext/gettextf,stop,warning andmessage calls. Some of these are likely to bespurious and so the file is likely to need manual editing.xgettext extracts the actual calls and so is more useful whentidying up error messages.

The R functionngettext provides an interface to the Cfunction of the same name: see example in the previous section. It issafest to usedomain="R-pkg" explicitly in calls tongettext, and necessary for earlier versions of R unless theyare calls directly from a function in the package.


Previous:, Up:Internationalization   [Contents][Index]

1.8.3 Preparing translations

Once the template files have been created, translations can be made.Conventional translations have file extension.po and are placedin thepo subdirectory of the package with a name that is either‘ll.po’ or ‘R-ll.po’ for translations of the C and Rmessages respectively to language with code ‘ll’.

SeeLocalization of messages inR Installation and Administrationfor details of language codes.

There is an R function,update_pkg_po in packagetools,to automate much of the maintenance of message translations. See itshelp for what it does in detail.

If this is called on a package with no existing translations, it createsthe directorypkgdir/po, creates a template file of Rmessages,pkgdir/po/R-pkg.pot, within it, creates the‘en@quot’ translation and installs that. (The ‘en@quot’pseudo-language interprets quotes in their directional forms in suitable(e.g. UTF-8) locales.)

If the package has C source files in itssrc directorythat are marked for translation, use

touchpkgdir/po/pkg.pot

to create a dummy template file, then callupdate_pkg_po again(this can also be done before it is called for the first time).

When translations to new languages are added in thepkgdir/podirectory, running the same command will check and theninstall the translations.

If the package sources are updated, the same command will update thetemplate files, merge the changes into the translation.po filesand then installed the updated translations. You will often see thatmerging marks translations as ‘fuzzy’ and this is reported in thecoverage statistics. As fuzzy translations arenot used, this isan indication that the translation files need human attention.

The merged translations are run throughtools::checkPofile tocheck that C-style formats are used correctly: if not the mismatches arereported and the broken translations are not installed.

This function needs the GNUgettext-tools installed and on thepath: see its help page.


Next:, Previous:, Up:Creating R packages   [Contents][Index]

1.9 CITATION files

An installed file namedCITATION will be used by thecitation() function. (It should be in theinstsubdirectory of the package sources.)

TheCITATION file is parsed as R code (in the package’sdeclared encoding, or inASCII if none is declared).It will contain calls to functionbibentry.Here is that fornlme:

## R package reference generated from DESCRIPTION metadatacitation(auto = meta)## NLME bookbibentry(bibtype = "Book",         title = "Mixed-Effects Models in S and S-PLUS",         author = c(person(c("José", "C."), "Pinheiro"),                    person(c("Douglas", "M."), "Bates")),         year = "2000", publisher = "Springer", address = "New York",         doi = "10.1007/b98882")

Note how the first call auto-generates citation informationfrom objectmeta, a parsed version of theDESCRIPTION file– it is tempting to hardcode such information, but it normally thengets outdated. How the first entry would look like as abibentrycall can be seen fromprint(citation("pkgname", auto = TRUE), style = "R")for any installed package. Auto-generated information isreturned by default if noCITATION file is present.

See?bibentry for further details of theinformation which can be provided.In case a bibentry contains LaTeX markup (e.g., for accentedcharacters or mathematical symbols), it may be necessary to provide atext representation to be used for printingvia thetextVersion argument tobibentry. E.g., earlier versionsofnlme additionally used something like

         textVersion =         paste0("Jose Pinheiro, Douglas Bates, Saikat DebRoy, ",                "Deepayan Sarkar and the R Core Team (",                sub("-.*", "", meta$Date),                "). nlme: Linear and Nonlinear Mixed Effects Models. ",                sprintf("R package version %s", meta$Version), ".")

TheCITATION file should itself produce no output whensource-d.

It is desirable (and essential forCRAN) that theCITATION file does not contain calls to functions such aspackageDescription which assume the package is installed in alibrary tree on the package search path.


Next:, Previous:, Up:Creating R packages   [Contents][Index]

1.10 Package types

TheDESCRIPTION file has an optional fieldType which ifmissing is assumed to be ‘Package’, the sort of extension discussedso far in this chapter. Currently one other type is recognized; thereused also to be a ‘Translation’ type.


Up:Package types   [Contents][Index]

1.10.1 Frontend

This is a rather general mechanism, designed for adding new front-endssuch as the formergnomeGUI package (see theArchive area onCRAN). If aconfigure file is found in the top-leveldirectory of the package it is executed, and then if aMakefileis found (often generated byconfigure),make is called.IfR CMD INSTALL --clean is usedmake clean is called. Noother action is taken.

R CMD build can package up this type of extension, butRCMD check will check the type and skip it.

Many packages of this type need write permission for the Rinstallation directory.


Previous:, Up:Creating R packages   [Contents][Index]

1.11 Services

Several members of the R project have set up services to assist thosewriting R packages, particularly those intended for publicdistribution.

win-builder.r-project.orgoffers the automated preparation of (‘x86_64’) Windows binaries fromwell-tested source packages.

R-Forge (R-Forge.r-project.org) andRForge (www.rforge.net) are similarservices with similar names. Both provide source-code managementthrough SVN, daily building and checking, mailing lists and a repositorythat can be accessedviainstall.packages (they can beselected bysetRepositories and the GUI menus that use it).Package developers have the opportunity to present their work on thebasis of project websites or news announcements. Mailing lists, forumsor wikis provide useRs with convenient instruments for discussions andfor exchanging information between developers and/or interested useRs.


Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

2 Writing R documentation files


Next:, Up:Writing R documentation files   [Contents][Index]

2.1 Rd format

R objects are documented in files written in “R documentation”(Rd) format, a simple markup language much of which closely resembles(La)TeX, which can be processed into a variety of formats,including LaTeX,HTML and plain text. The translation iscarried out by functions in thetools package called by thescriptRdconv inR_HOME/bin and by theinstallation scripts for packages.

The R distribution contains more than 1400 such files which can befound in thesrc/library/pkg/man directories of the Rsource tree, wherepkg stands for one of the standard packageswhich are included in the R distribution.

As an example, let us look at a simplified version ofsrc/library/base/man/load.Rd which documents the R functionload.

% File src/library/base/man/load.Rd\name{load}\alias{load}\title{Reload Saved Datasets}\description{  Reload datasets written with the function \code{save}.}\usage{load(file, envir = parent.frame(), verbose = FALSE)}\arguments{  \item{file}{a (readable binary-mode) \link{connection}    or a character string giving the name of the file to load    (when \link{tilde expansion} is done).}  \item{envir}{the environment where the data should be loaded.}  \item{verbose}{should item names be printed during loading?}}\value{  A character vector of the names of objects created, invisibly.}\seealso{  \code{\link{save}}.}\examples{## save all datasave(list = ls(all.names = TRUE), file = "all.RData")## restore the saved values to the current environmentload("all.RData")}\keyword{file}

AnRd file consists of three parts. The header gives basicinformation about the name of the file, the topics documented, a title,a short textual description and R usage information for the objectsdocumented. The body gives further information (for example, on thefunction’s arguments and return value, as in the above example).Finally, there is an optional footer with keyword information. Theheader is mandatory.

Information is given within a series ofsections with standardnames (and user-defined sections are also allowed). Unless otherwisespecified118 these should occur only once in anRdfile (in any order), and the processing software will retain only thefirst occurrence of a standard section in the file, with a warning.

See“Guidelines for Rdfiles” for guidelines for writing documentation inRd formatwhich should be useful for package writers.The Rgeneric functionprompt is used to construct a bare-bonesRdfile ready for manual editing. Methods are defined for documentingfunctions (which fill in the proper function and argument names) anddata frames. There are also functionspromptData,promptPackage,promptClass, andpromptMethods forother types ofRd files.

The general syntax ofRd files is summarized below. For a detailedtechnical discussion of currentRd syntax, see“Parsing Rd files”.

Rd files consist of four types of text input. The most commonis LaTeX-like, with the backslash used as a prefix on markup(e.g.\alias), and braces used to indicate arguments(e.g.{load}). The least common type of text is ‘verbatim’text, where no markup other than the comment marker (%) isprocessed. There is also a rare variant of ‘verbatim’ text(used in\eqn,\deqn,\figure,and\newcommand) where comment markers need not be escaped.The final type is R-like, intended for R code, but allowing someembedded macros. Quoted strings within R-like text are handledspecially: regular character escapes such as\n may be enteredas-is. Only markup starting with\l (e.g.\link) or\v (e.g.\var) will be recognized within quoted strings.The rarely used vertical tab\v must be entered as\\v.

Each macro defines the input type for its argument. For example, thefile initially uses LaTeX-like syntax, and this is also used in the\description section, but the\usage section usesR-like syntax, and the\alias macro uses ‘verbatim’ syntax.Comments run from a percent symbol% to the end of the line inall types of text except the rare ‘verbatim’ variant(as on the first line of theload example).

Because backslashes, braces and percent symbols have special meaning, toenter them into text sometimes requires escapes using a backslash. Ingeneral balanced braces do not need to be escaped, but percent symbolsalways do, except in the ‘verbatim’ variant.For the complete list of macros and rules for escapes, see“Parsing Rd files”.


Next:, Up:Rd format   [Contents][Index]

2.1.1 Documenting functions

The basic markup commands used for documenting R objects (inparticular, functions) are given in this subsection.

\name{name}

name typically119 is the basename oftheRd file containing the documentation. It is the “name” oftheRd object represented by the file and has to be unique in apackage. To avoid problems with indexing the package manual, it may notcontain ‘!’ ‘|’ nor ‘@’.(LaTeX special characters are allowed, but may not be collatedcorrectly in the index.) There can only be one\name entry in afile, and it must not contain any markup and should only containprintableASCII characters. Entries in the package manualwill be in alphabetic120 orderof the\name entries.

\alias{topic}

The\alias sections specify all “topics” the file documents.This information is collected into index data bases for lookup by theon-line (plain text andHTML) help systems. Thetopic cancontain spaces, but (for historical reasons) leading and trailing spaceswill be stripped. Percent and left brace need to be escaped bya backslash.

There may be several\alias entries. Quite often it isconvenient to document several R objects in one file. For example,fileNormal.Rd documents the density, distribution function,quantile function and generation of random variates for the normaldistribution, and hence starts with

Also, it is often convenient to have several different ways to refer toan R object, and an\alias does not need to be the name of anobject.

Note that the\name is not necessarily a topic documented, and ifso desired it needs to have an explicit\alias entry (as in thisexample).

\title{Title}

Title information for theRd file. This should be capitalizedand not end in a period; try to limit its length to at most 65characters for widest compatibility.

Markup is supported in the text, but use of characters other thanEnglish text and punctuation (e.g., ‘<’) may limit portability.

There must be one (and only one)\title section in a help file.

\description{…}

A short description of what the function(s) do(es) (one paragraph, a fewlines only). (If a description is too long and cannot easily beshortened, the file probably tries to document too much at once.)This is mandatory except for package-overview files.

\usage{fun(arg1,arg2, …)}

One or more lines showing the synopsis of the function(s) and variablesdocumented in the file. These are set in typewriter font. This is anR-like command.

The usage information specified should match the function definitionexactly (such that automatic checking for consistency betweencode and documentation is possible).

To indicate that a function can be used in several different ways,depending on the named arguments specified, use section\details.E.g.,abline.Rd contains

\details{  Typical usages are\preformatted{abline(a, b, ...)......}

Use\method{generic}{class} to indicate the nameof an S3 method for the generic functiongeneric for objectsinheriting from class"class". In the printed versions,this will come out asgeneric (reflecting the understanding thatmethods should not be invoked directly butvia method dispatch), butcodoc() and other QC tools always have access to the full name.

For example,print.ts.Rd contains

\usage{\method{print}{ts}(x, calendar, \dots)}

which will print as

Usage:     ## S3 method for class 'ts':     print(x, calendar, ...)

Usage for replacement functions should be given in the style ofdim(x) <- value rather than explicitly indicating the name of thereplacement function ("dim<-" in the above). Similarly, onecan use\method{generic}{class}(arglist) <-value to indicate the usage of an S3 replacement method for the genericreplacement function"generic<-" for objects inheritingfrom class"class".

Usage for S3 methods for extracting or replacing parts of an object, S3methods for members of the Ops group, and S3 methods for user-defined(binary) infix operators (‘%xxx%’) follows the above rules,using the appropriate function names. E.g.,Extract.factor.Rdcontains

\usage{\method{[}{factor}(x, \dots, drop = FALSE)\method{[[}{factor}(x, \dots)\method{[}{factor}(x, \dots) <- value}

which will print as

Usage:     ## S3 method for class 'factor':     x[..., drop = FALSE]     ## S3 method for class 'factor':     x[[...]]     ## S3 replacement method for class 'factor':     x[...] <- value

\S3method is accepted as an alternative to\method.

\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. (Note that there isno whitespace between the three parts of the entry.) Arguments can alsobe described jointly by separating their names with commas (and optionalwhitespace) in the\item label. There may beoptional text outside the\item entries, for example to givegeneral information about groups of parameters.

\details{…}

A detailed if possible precise description of the functionalityprovided, extending the basic information in the\descriptionslot.

\value{…}

Description of the function’s return value.

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

\item{comp_i}{Description of comp_i.}

for each component of the list returned. There may beoptional text outside the\item entries(see for example the joint help forrle andinverse.rle,or the sets of items inl10n_info). Note that\valueis implicitly a\describe environment, so that environment shouldnot be used for listing components, just individual\item{}{}entries.121

\references{…}

A section with references to the literature. Use\url{} or\href{}{} for web pointers, and\doi{} forDOIs(this needs R >= 3.3, seeUser-defined macros for more info).

\note{...}

Use this for a special note you want to have pointed out. Multiple\note sections are allowed, but might be confusing to the end users.

For example,pie.Rd contains

\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 theRd file. Use\email{} without extra delimiters (such as ‘( )’ or‘< >’) to specify email addresses, or\url{} or\href{}{} for web pointers.

\seealso{…}

Pointers to related R objects, using\code{\link{...}} torefer to them (\code is the correct markup for R object names,and\link produces hyperlinks in output formats which supportthis. SeeMarking text, andCross-references).

\examples{…}

Examples of how to use the function. Code in this section is setin typewriter font without reformatting and is run byexample() unless marked otherwise (see below).

Examples are not only useful for documentation purposes, but alsoprovide test code used for diagnostic checking of R code. Bydefault, text inside\examples{} will be displayed in theoutput of the help page and run byexample() and byR CMDcheck. You can use\dontrun{}for text that should only be shown, but not run, and\dontshow{}for extra commands for testing that should not be shown to users, butwill be run byexample(). (Previously this was called\testonly, and that is still accepted.)

Text inside\dontrun{} is ‘verbatim’, but the other partsof the\examples section are R-like text.

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 requirespecial facilities (such as Internet access or write permission tospecific directories). Text included in\dontrun is indicated bycomments in the processed help files: it need not be valid R code butthe escapes must still be used for%,\ and unpairedbraces as in other ‘verbatim’ text.

Example code must be capable of being run byexample, which usessource. This means that it should not accessstdin,e.g. toscan() data from the example file.

Data needed for making the examples executable can be obtained by randomnumber generation (for example,x <- rnorm(100)), or by usingstandard data sets listed bydata() (see?data for moreinfo).

Finally, there is\donttest, used (at the beginning of a separateline) to mark code that should be run byexample() but not byR CMD check (by default: the option--run-donttest canbe used). This should be needed only occasionally but can be used forcode which might fail in circumstances that are hard to test for, forexample in some locales. (Use e.g.capabilities() ornzchar(Sys.which("someprogram")) to test for features needed inthe examples wherever possible, and you can also usetry() ortryCatch(). Useinteractive() to condition examples whichneed someone to interact with.) Note that code included in\donttest must be correct R code, and any packages used shouldbe declared in theDESCRIPTION file. It is good practice toinclude a comment in the\donttest section explaining why it isneeded.

Output from code marked with\dontdiff (requires R >= 4.4.0)or between comment lines

## IGNORE_RDIFF_BEGIN## IGNORE_RDIFF_END

is ignored when comparing check output to reference output (apkg-Ex.Rout.save file).The comment-based markup can also be used for scripts undertests.

\keyword{key}

There can be zero or more\keyword sections per file.Each\keyword section should specify a single keyword, preferablyone of the standard keywords as listed in fileKEYWORDS in theR documentation directory (defaultR_HOME/doc). Usee.g.RShowDoc("KEYWORDS") to inspect the standard keywords fromwithin R. There can be more than one\keyword entry if the Robject being documented falls into more than one category, or none.

Do strongly consider using\concept (seeIndices) instead of\keyword if you are about to use more than very few non-standardkeywords.

The special keyword ‘internal’ marks a page of internal topics(typically, objects that are not part of the package’s API).If the help page for topicfoo has keyword ‘internal’, thenhelp(foo) gives thishelp page, butfoo is excluded from several topic indices,including the alphabetical list of topics in theHTML help system.

help.search() can search by keyword, including user-definedvalues: however the ‘Search Engine & Keywords’HTML page accessedviahelp.start() provides single-click access only to apre-defined list of keywords.


Next:, Previous:, Up:Rd format   [Contents][Index]

2.1.2 Documenting data sets

The structure ofRd files which document R data sets is slightlydifferent. Sections such as\arguments and\value are notneeded but the format and source of the data should be explained.

As an example, let us look atsrc/library/datasets/man/rivers.Rdwhich documents the standard R data setrivers.

\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{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}

This uses the following additional markup commands.

\docType{…}

Indicates the “type” of the documentation object. Always ‘data’for data sets, and ‘package’ forpkg-package.Rdoverview files. Documentation for S4 methods and classes uses‘methods’ (frompromptMethods()) and ‘class’ (frompromptClass()).

\format{…}

A description of the format of the data set (as a vector, matrix, dataframe, time series, …). For matrices and data frames this shouldgive a description of each column, preferably as a list or table.SeeLists and tables, for more information.

\source{…}

Details of the original source (a reference orURL,seeSpecifying URLs). In addition, section\references couldgive secondary sources and usages.

Note also that when documenting data setbar,

  • The\usage entry is alwaysbar or (for packageswhich do not use lazy-loading of data)data(bar). (Inparticular, only document asingle data object perRd file.)
  • The\keyword entry should always be ‘datasets’.

Ifbar is a data frame, documenting it as a data set canbe initiatedviaprompt(bar). Otherwise, thepromptDatafunction may be used.


Next:, Previous:, Up:Rd format   [Contents][Index]

2.1.3 Documenting S4 classes and methods

There are special ways to use the ‘?’ operator, namely‘class?topic’ and ‘methods?topic’, to accessdocumentation for S4 classes and methods, respectively. This mechanismdepends on conventions for the topic names used in\aliasentries. The topic names for S4 classes and methods respectively are ofthe form

class-classgeneric,signature_list-method

wheresignature_list contains the names of the classes in thesignature of the method (without quotes) separated by ‘,’ (withoutwhitespace), with ‘ANY’ used for arguments without an explicitspecification. E.g., ‘genericFunction-class’ is the topic name fordocumentation for the S4 class"genericFunction", and‘coerce,ANY,NULL-method’ is the topic name for documentation forthe S4 method forcoerce for signaturec("ANY", "NULL").

Skeletons of documentation for S4 classes and methods can be generatedby using the functionspromptClass() andpromptMethods()from packagemethods. If it is necessary or desired to provide anexplicit function declaration (in a\usage section) for an S4method (e.g., if it has “surprising arguments” to be mentionedexplicitly), one can use the special markup

\S4method{generic}{signature_list}(argument_list)

(e.g., ‘\S4method{coerce}{ANY,NULL}(from, to)’).

To make full use of the potential of the on-line documentation system,all user-visible S4 classes and methods in a package should at leasthave a suitable\alias entry in one of the package’sRd files.If a package has methods for a function defined originally somewhereelse, and does not change the underlying default method for thefunction, the package is responsible for documenting the methods itcreates, but not for the function itself or the default method.

An S4 replacement method is documented in the same way as an S3 one: seethe description of\method inDocumenting functions.

Seehelp("Documentation", package = "methods") for moreinformation on using and creating on-line documentation for S4 classes andmethods.


Previous:, Up:Rd format   [Contents][Index]

2.1.4 Documenting packages

Packages may have an overview help page with an\aliaspkgname-package, e.g. ‘utils-package’ for theutils package, whenpackage?pkgname will open thathelp page. If a topic namedpkgname does not exist inanotherRd file, it is helpful to use this as an additional\alias.

Skeletons of documentation for a package can be generated using thefunctionpromptPackage(). If thefinal = TRUE argumentis used, then theRd file will be generated in final form, containingonly basic information from theDESCRIPTION file. Otherwise (thedefault) comments will be inserted giving suggestions for content.

Apart from the mandatory\name and\title and thepkgname-package alias, the only requirement for the packageoverview page is that it include a\docType{package} statement.All other content is optional. We suggest that it should be a shortoverview, to give a reader unfamiliar with the package enoughinformation to get started. More extensive documentation is betterplaced into a package vignette (seeWriting package vignettes) andreferenced from this page, or into individual man pages for thefunctions, datasets, or classes.


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.2 Sectioning

To begin a new paragraph or leave a blank line in an example, justinsert 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 (thefirst argument to\section) should be capitalized (but not allupper case) and not end in a period.Whitespace between the first and second braced expressionsis not allowed. Markup (e.g.\code) within the section titlemay cause problems with the latex conversion (depending on the versionof macro packages such as ‘hyperref’) and so should be avoided.

The\subsection macro takes arguments in the same format as\section, but is used within a section, so it may be used tonest subsections within sections or other subsections. There is nopredefined limit on the nesting level, but formatting is not designedfor more than 3 levels (i.e. subsections within subsections withinsections).

Note that additional named sections are always inserted at a fixedposition in the output (before\note,\seealso and theexamples), no matter where they appear in the input (but in the sameorder amongst themselves as in the input).


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.3 Marking text

The following logical markup commands are available for emphasizing orquoting text.

\emph{text}
\strong{text}

Emphasizetext usingitalic andbold font ifpossible;\strong is regarded as stronger (more emphatic).

\bold{text}

Settext inbold font where possible.

\sQuote{text}
\dQuote{text}

Portably single or double quotetext (without hard-wiring thecharacters used for quotation marks).

Each of the above commands takes LaTeX-like input, so other macrosmay be used withintext.

The following logical markup commands are available for indicatingspecific kinds of text. Except as noted, these take ‘verbatim’ textinput, and so other macros may not be used within them. Some characterswill need to be escaped (seeInsertions).

\code{text}

Indicate text that is a literal example of a piece of an R program,e.g., a fragment of R code or the name of an R object. Text isentered in R-like syntax, and displayed usingtypewriter fontwhere possible. Macros\var and\link are interpreted withintext.

\preformatted{text}

Indicate text that is a literal example of a piece of a program. Textis displayed usingtypewriter font where possible. Formatting,e.g. line breaks, is preserved. (Note that this includes a line breakafter the initial {, so typically text should start on the same line asthe command.)

Due to limitations in LaTeX as of this writing, this macro may not benested within other markup macros other than\dQuote and\sQuote, as errors or bad formatting may result.

\kbd{keyboard-characters}

Indicate keyboard input, usingslanted typewriter font ifpossible, so users can distinguish the characters they are supposed totype from computer output. Text is entered ‘verbatim’.

\samp{text}

Indicate text that is a literal example of a sequence of characters,entered ‘verbatim’, to be included within word-wrapped text. Displayedwithin single quotation marks andusingtypewriter font where possible.

\verb{text}

Indicate text that is a literal example of a sequence of characters,entered ‘verbatim’. No wrapping or reformatting will occur. Displayedusingtypewriter font where possible.

\pkg{package_name}

Indicate the name of an R package. LaTeX-like.

\file{file_name}

Indicate the name of a file. Text is LaTeX-like, so backslash needsto be escaped. Displayed using a distinct font where possible.

\email{email_address}

Indicate an electronic mail address. LaTeX-like, will be rendered asa hyperlink inHTML and PDF conversion. Displayed usingtypewriter font where possible.

\url{uniform_resource_locator}

Indicate a uniform resource locator (URL) for the World WideWeb. The argument is handled as ‘verbatim’ text (with percent andbraces escaped by backslash), and rendered as a hyperlink inHTML andPDF conversion. Line feeds are removed, and leading and trailingwhitespace122 isremoved. SeeSpecifying URLs.

Displayed usingtypewriter font where possible.

\href{uniform_resource_locator}{text}

Indicate a hyperlink to the World Wide Web. The first argument ishandled as ‘verbatim’ text (with percent and braces escaped bybackslash) and is used as theURL in the hyperlink, with thesecond argument of LaTeX-like text displayed to the user. Line feedsare removed from the first argument, and leading and trailing whitespaceis removed.

Note that RFC3986-encoded URLs (e.g. using ‘%28VS.85%29’ inplace of ‘(VS.85)’) may not work correctly in versions of Rbefore 3.1.3 and are best avoided—useURLdecode() to decodethem.

\var{metasyntactic_variable}

Indicate a metasyntactic variable. In most cases this will be rendereddistinctly, e.g. in italic (PDF/HTML) or wrapped in ‘<…>’ (text),but not in all123. LaTeX-like.

\env{environment_variable}

Indicate an environment variable. ‘Verbatim’.Displayed usingtypewriter font where possible

\option{option}

Indicate a command-line option. ‘Verbatim’.Displayed usingtypewriter font where possible.

\command{command_name}

Indicate the name of a command. LaTeX-like, so\var isinterpreted. Displayed usingtypewriter font where possible.

\dfn{term}

Indicate the introductory or defining use of a term. LaTeX-like.

\cite{reference}

Indicate a reference without a direct cross-referencevia\link(seeCross-references), such as the name of a book. LaTeX-like.

\acronym{acronym}

Indicate an acronym (an abbreviation written in all capital letters),such asGNU. LaTeX-like.

\abbr{abbr}

Indicates an abbreviation. LaTeX-like.


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.4 Lists and tables

The\itemize and\enumerate commands take a singleargument, within which there may be one or more\item commands.The text following each\item is formatted as one or moreparagraphs, suitably indented and with the first paragraph marked with abullet point (\itemize) or a number (\enumerate).

Note that unlike argument lists,\item in these formats isfollowed by a space and the text (not enclosed in braces). For example

  \enumerate{    \item A database consists of one or more records, each with one or    more named fields.    \item Regular lines start with a non-whitespace character.    \item Records are separated by one or more empty lines.  }

\itemize and\enumerate commands may be nested.

The\describe command is similar to\itemize but allowsinitial labels to be specified. Each\item takes two arguments,the label and the body of the item, in exactly the same way as anargument or value\item.\describe commands are mapped to<DL> lists inHTML and\description lists in LaTeX.

Using these without any\items may cause problems with someconversions and makes little sense.

The\tabular command takes two arguments. The first gives foreach of the columns the required alignment (‘l’ forleft-justification, ‘r’ for right-justification or ‘c’ forcentring.) The second argument consists of an arbitrary number oflines 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 arealignments in the first argument, and they must be non-empty (but cancontain only spaces). (There is no whitespace between\tabularand the first argument, nor between the two arguments.)


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.5 Cross-references

The markup\link{foo} (usually in the combination\code{\link{foo}}) produces a hyperlink to the help forfoo. Herefoo is atopic, that is the argument of\alias markup in anotherRd file (possibly in another package).Hyperlinks are supported in some of the formats to whichRd files areconverted, for exampleHTML and PDF, but ignored in others, e.g.the text format.

One main usage of\link is in the\seealso section of thehelp page, seeRd format.

Note that whereas leading and trailing spaces are stripped whenextracting a topic from a\alias, they are not stripped whenlooking up the topic of a\link.

You can specify a link to a different topic than its name by\link[=dest]{name} which links to topicdestwith namename. This can be used to refer to the documentationfor S3/4 classes, for example\code{"\link[=abc-class]{abc}"}would be a way to refer to the documentation of an S4 class"abc"defined in your package, and\code{"\link[=terms.object]{terms}"} to the S3"terms"class (in packagestats). To make these easy to read in thesource file,\code{"\linkS4class{abc}"} expands to the formgiven above.

There are two other forms with an optional ‘anchor’ argument, specified as\link[pkg]{foo} and\link[pkg:bar]{foo}, to link to topicsfoo andbar respectively in the packagepkg. They are currently only used inHTML help (andignored for hyperlinks in LaTeX conversions of help pages). Oneshould be careful about topics containing special characters (such asarithmetic operators) as they may result in unresolvable links, andpreferably use a safer alias in the same help page.

Historically (before R version 4.1.0), links of the form\link[pkg]{foo} and\link[pkg:bar]{foo} used to be interpreted as linkstofilesfoo.html andbar.html inpackagepkg, respectively. For this reason, theHTML helpsystem looks for filefoo.html in packagepkgif it does not find topicfoo, and then searches for thetopic in other installed packages. To test that links work both withboth old and new systems, the pre-4.1.0 behaviour can be restored bysetting the environment variable_R_HELP_LINKS_TO_TOPICS_=false.

Packages referred to by these ‘other forms’ should be declared in theDESCRIPTION file, in the ‘Depends’, ‘Imports’,‘Suggests’ or ‘Enhances’ fields.


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.6 Mathematics

Mathematical formulae should be set beautifully for printeddocumentation and in KaTeX/MathJax-enhancedHTML help (as fromR 4.2.0) yet we still want something useful for plain-text (andlegacyHTML) help. To this end, the two commands\eqn{latex}{ascii} and\deqn{latex}{ascii} are used. Whereas\eqnis used for “inline” formulae (corresponding to TeX’s$…$),\deqn gives “displayed equations” (as inLaTeX’sdisplaymath environment, or TeX’s$$…$$). Both arguments are treated as ‘verbatim’ text.

Both commands can also be used as\eqn{latexascii} (onlyone argument) which then is used for bothlatex andascii. No whitespace is allowed between command and the firstargument, nor between the first and second arguments.

The following example is fromPoisson.Rd:

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

In plain-text help we get

    p(x) = lambda^x exp(-lambda)/x!for x = 0, 1, 2, ....

In legacyHTML help, Greek letters (both cases) will be rendered if preceded by abackslash,\dots and\ldots will be rendered as ellipsesand\sqrt,\ge and\le as mathematical symbols.

Note that only basic LaTeX can be used, there being no provision tospecify LaTeX style files, butAMS extensions are supportedas from R 4.2.2.


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.7 Figures

To include figures in help pages, use the\figure markup. Thereare three forms.

The two commonly used simple forms are\figure{filename}and\figure{filename}{alternate text}. This willinclude a copy of the figure in eitherHTML or LaTeX output. In textoutput, the alternate text will be displayed instead. (When the secondargument is omitted, the filename will be used.) Both the filename andthe alternate text will be parsed verbatim, and should not includespecial characters that are significant inHTML or LaTeX.

The expert form is\figure{filename}{options:string}. (The word ‘options:’ must be typed exactly asshown and followed by at least one space.) In this form, thestring is copied into theHTMLimg tag as attributesfollowing thesrc attribute, or into the second argument of the\Figure macro in LaTeX, which by default is used as options toan\includegraphics call. As it is unlikely that any singlestring would suffice for both display modes, the expert form wouldnormally be wrapped in conditionals. It is up to the author to makesure that legalHTML/LaTeX is used. For example, to include alogo in bothHTML (using the simple form) and LaTeX (using theexpert form), the following could be used:

\if{html}{\figure{Rlogo.svg}{options: width=100 alt="R logo"}}\if{latex}{\figure{Rlogo.pdf}{options: width=0.5in}}

The files containing the figures should be stored in the directoryman/figures. Files with extensions.jpg,.jpeg,.pdf,.png and.svg from that directory will becopied to thehelp/figures directory at install time. (Figures inPDF format will not display in mostHTML browsers, but might be thebest choice in reference manuals.) Specify the filename relative toman/figures in the\figure directive.


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.8 Insertions

Use\R for the R system itself. The\dotsmacro is a historical alternative to using literal ‘...’for the dots in function argument lists; use\ldotsfor ellipsis dots in ordinary text.124 These macros can be followed by{}, and should be unless followed by whitespace.

After an unescaped ‘%’, you can put your own comments regarding thehelp text. The rest of the line (but not the newline at the end) willbe completely disregarded. Therefore, you can also use it to make partof the “help” invisible.

You can produce a backslash (‘\’) by escaping it by anotherbackslash. (Note that\cr is used for generating line breaks.)

The “comment” character ‘%’ and unpaired braces125almost always need to be escaped by ‘\’, and ‘\\’ canbe used for backslash and needs to be when there are two or more adjacentbackslashes. In R-like code quoted strings are handled slightlydifferently; see“Parsing Rd files” for details – in particular braces should not beescaped in quoted strings.

All of ‘% { } \’ should be escaped in LaTeX-like text.

Text which might need to be represented differently in differentencodings should be marked by\enc, e.g.\enc{Jöreskog}{Joreskog} (with no whitespace between thebraces) where the first argument will be used where encodings areallowed and the second should beASCII (and is used for e.g.the text conversion in locales that cannot represent the encoded form).(This is intended to be used for individual words, not whole sentencesor paragraphs.)


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.9 Indices

The\alias command (seeDocumenting functions) is used tospecify the “topics” documented, which should includeall Robjects in a package such as functions and variables, data sets, and S4classes and methods (seeDocumenting S4 classes and methods). Theon-line help system searches the index data base consisting of allalias topics.

In addition, it is possible to provide “concept index entries” using\concept, which can be used forhelp.search() lookups.E.g., filecor.test.Rd in the standard packagestatscontains

\concept{Kendall correlation coefficient}\concept{Pearson correlation coefficient}\concept{Spearman correlation coefficient}

so that e.g.??Spearman will succeed in finding thehelp page for the test for association between paired samples usingSpearman’s rho.

(Note thathelp.search() only uses “sections” of documentationobjects with no additional markup.)

Each\concept entry should give asingle index term (wordor phrase), and not use any Rd markup.

If you want to cross reference such items from other help filesvia\link, you need to use\alias and not\concept.


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.10 Platform-specific documentation

Sometimes the documentation needs to differ by platform. Currently twoOS-specific options are available, ‘unix’ and ‘windows’, andlines in the help source file can be enclosed in

#ifdefOS   ...#endif

or

#ifndefOS   ...#endif

for OS-specific inclusion or exclusion. Such blocks should not benested, and should be entirely within a block (that, is between theopening and closing brace of a section or item), or at top-level containone or more complete sections.

If the differences between platforms are extensive or the R objectsdocumented are only relevant to one platform, platform-specificRd filescan be put in aunix orwindows subdirectory.


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.11 Conditional text

Occasionally the best content for one output format is different fromthe best content for another. For this situation, the\if{format}{text} or\ifelse{format}{text}{alternate} markupis used. Hereformat is a comma separated list of formats inwhich thetext should be rendered. Thealternate will berendered if the format does not match. Bothtext andalternate may be any sequence of text and markup.

Currently the following formats are recognized:example,html,latex andtext. These select output forthe corresponding targets. (Note thatexample refers toextracted example code rather than the displayed example in some otherformat.) Also accepted areTRUE (matching all formats) andFALSE (matching no formats). These could be the outputof the\Sexpr macro (seeDynamic pages).

The\out{literal} macro would usually be used withinthetext part of\if{format}{text}. Itcauses the renderer to output the literal text exactly, with noattempt to escape special characters. For example, usethe following to output the markup necessary to display the Greek letter inLaTeX orHTML, and the text stringalpha in other formats:

\ifelse{latex}{\out{$\alpha$}}{\ifelse{html}{\out{&alpha;}}{alpha}}

Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.12 Dynamic pages

Two macros supporting dynamically generated man pages are\Sexprand\RdOpts. These are modelled after Sweave, and are intendedto contain executable R expressions in theRd file.

The main argument to\Sexpr must be valid R code that can beexecuted. It may also take options in square brackets before the mainargument. Depending on the options, the code may be executed atpackage build time, package install time, or man page rendering time.

The options follow the same format as in Sweave, but different optionsare supported. Currently the allowed options and their defaults are:

  • eval=TRUEWhether the R code should be evaluated.
  • echo=FALSEWhether the R code should be echoed. IfTRUEandresults=verbatim, a display willbe given in a preformatted block. For example,\Sexpr[echo=TRUE,results=verbatim]{ x <- 1 } will be displayed as
    > x <- 1
  • keep.source=TRUEWhether to keep the author’s formatting when displaying thecode, or throw it away and use a deparsed version.
  • results=textHow should the results be displayed? The possibilitiesare:
    • results=textApplyas.character() to the result of the code, and insert itas a text element.
    • results=verbatimPrint the results of the code just as if it was executed at the console,and include the printed results verbatim. (Invisible results will not print.)
    • results=rdThe result is assumed to be a character vector containing markup to bepassed toparse_Rd(), with the result inserted in place. Thiscould be used to insert computed aliases, for instance.parse_Rd() is called first withfragment = FALSE to allowa single Rd section macro to be inserted. If that fails, it is calledagain withfragment = TRUE, the older behavior.
    • results=hideInsert no output.
  • strip.white=trueRemove leading and trailing blank lines in verbatimoutput ifstrip.white=true (orTRUE). Withstrip.white=all, remove all blank lines.
  • stage=installControl when this macro is run. Possible values are
    • stage=buildThe macro is run when building a source tarball.
    • stage=installThe macro is run when installing from source.
    • stage=renderThe macro is run when displaying the help page.

    Conditionals such as#ifdef(seePlatform-specific documentation) are applied after thebuild macros but before theinstall macros. In somesituations (e.g. installing directly from a source directory without atarball, or building a binary package) the above description is notliterally accurate, but authors can rely on the sequence beingbuild,#ifdef,install,render, with allstages executed.

    Code is only run once in each stage, so a\Sexpr[results=rd]macro can output an\Sexpr macro designed for a later stage,but not for the current one or any earlier stage.

  • width, height, figThese options are currently allowed but ignored.

The\RdOpts macro is used to set new defaults for options to applyto following uses of\Sexpr.

For more details, see the online document“Parsing Rd files”.


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.13 User-defined macros

The\newcommand and\renewcommand macros allow new macrosto be defined within an Rd file. These are similar but not identical tothe same-named LaTeX macros.

They each take two arguments which are parsed verbatim. The first isthe name of the new macro including the initial backslash, and thesecond is the macro definition. As in LaTeX,\newcommandrequires that the new macro not have been previously defined, whereas\renewcommand allows existing macros (including all built-inones) to be replaced. (This test is disabled by default, but may beenabled by setting the environment variable_R_WARN_DUPLICATE_RD_MACROS_ to a true value.)

Also as in LaTeX, the new macro may be defined to take arguments,and numeric placeholders such as#1 are used in the macrodefinition. However, unlike LaTeX, the number of arguments isdetermined automatically from the highest placeholder number seen inthe macro definition. For example, a macro definition containing#1 and#3 (but no other placeholders) will define athree argument macro (whose second argument will be ignored). As inLaTeX, at most 9 arguments may be defined. If the#character is followed by a non-digit it will have no specialsignificance. All arguments to user-defined macros will be parsed asverbatim text, and simple text-substitution will be used to replacethe place-holders, after which the replacement text will be parsed.

A number of macros are defined in the fileshare/Rd/macros/system.Rd of the R source or home directory,and these will normally be available in all.Rd files. Forexample, that file contains the definition

\newcommand{\PR}{\Sexpr[results=rd]{tools:::Rd_expr_PR(#1)}}

which defines\PR to be a single argument macro; then code(typically used in theNEWS.Rd file) like

\PR{1234}

will expand to

\Sexpr[results=rd]{tools:::Rd_expr_PR(1234)}

when parsed.

Some macros that might be of general use are:

\CRANpkg{pkg}

A package on CRAN

\sspace

A single space (used after a period that does not end a sentence).

\doi{identifier}

A digital object identifier (DOI).

See thesystem.Rd file inshare/Rd/macros for more detailsand macro definitions, including macros\packageTitle,\packageDescription,\packageAuthor,\packageMaintainer,\packageDESCRIPTION and\packageIndices.

Packages may also define their own common macros; these would be storedin an.Rd file inman/macros in the package source andwill be installed intohelp/macros when the package is installed.A package may also use the macros from a different package by listingthe other package in the ‘RdMacros’ field in theDESCRIPTIONfile.


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.14 Encoding

Rd files are text files and so it is impossible to deduce the encodingthey are written in unlessASCII: files with 8-bit characterscould be UTF-8, Latin-1, Latin-9, KOI8-R, EUC-JP,etc. So an\encoding{} section must be used to specify the encoding if itis notASCII. (The\encoding{} section must be on aline by itself, and in particular one containing no non-ASCIIcharacters. The encoding declared in theDESCRIPTION file willbe used if none is declared in the file.) TheRd files areconverted to UTF-8 before parsing and so the preferred encoding for thefiles themselves is now UTF-8.

Wherever possible, avoid non-ASCII chars inRd files, andeven symbols such as ‘<’, ‘>’, ‘$’, ‘^’, ‘&’,‘|’, ‘@’, ‘~’, and ‘*’ outside ‘verbatim’environments (since they may disappear in fonts designed to rendertext). (FunctionshowNonASCIIfile in packagetools can helpin finding non-ASCII bytes in the files.)

For convenience, encoding names ‘latin1’ and ‘latin2’ arealways recognized: these and ‘UTF-8’ are likely to work fairlywidely. However, this does not mean that all characters in UTF-8 willbe recognized, and the coverage of non-Latin characters126 is fairly low. Using LaTeXinputenx (see?Rd2pdf in R) will give greater coverageof UTF-8.

The\enc command (seeInsertions) can be used to providetransliterations which will be used in conversions that do not supportthe declared encoding.

The LaTeX conversion converts the file to UTF-8 from the declaredencoding, and includes a

\inputencoding{utf8}

command, and this needs to be matched by a suitable invocation of the\usepackage{inputenc} command. The R utilityRCMD Rd2pdf looks at the converted code and includes the encodings used:it might for example use

\usepackage[utf8]{inputenc}

(Use ofutf8 as an encoding requires LaTeX dated 2003/12/01 orlater. Also, the use of Cyrillic characters in ‘UTF-8’ appears toalso need ‘\usepackage[T2A]{fontenc}’, andR CMD Rd2pdfincludes this conditionally on the filet2aenc.def being presentand environment variable_R_CYRILLIC_TEX_ being set.)

Note that this mechanism works best with Latin letters: the coverage ofUTF-8 in LaTeX is quite low.


Next:, Previous:, Up:Writing R documentation files   [Contents][Index]

2.15 Processing documentation files

There are several commands to process Rd files from the system commandline.

UsingR CMD Rdconv one can convert R documentation format toother formats, or extract the executable examples for run-time testing.The currently supported conversions are to plain text,HTML andLaTeX as well as extraction of the examples.

R CMD Rd2pdf generates PDF output from documentation inRdfiles, which can be specified either explicitly or by the path to adirectory with the sources of a package. In the latter case, areference manual for all documented objects in the package is created,including the information in theDESCRIPTION files.

R CMD Sweave andR CMD Stangle process vignette-likedocumentation files (e.g. Sweave vignettes with extension‘.Snw’ or ‘.Rnw’, or other non-Sweave vignettes).R CMD Stangle is used to extract the R code fragments.

The exact usage and a detailed list of available options for all ofthese commands can be obtained by runningR CMDcommand--help, e.g.,R CMD Rdconv --help. All available commands can belisted usingR --help (orRcmd --help under Windows).

All of these work under Windows. You may need to have installed thethe tools to build packages from source as described in the “RInstallation and Administration” manual, although typically all that isneeded is a LaTeX installation.


Previous:, Up:Writing R documentation files   [Contents][Index]

2.16 Editing Rd files

It can be very helpful to prepare.Rd files using a editor whichknows about their syntax and will highlight commands, indent to show thestructure and detect mis-matched braces, and so on.

The system most commonly used for this is some version ofEmacs (includingXEmacs) with theESSpackage (https://ESS.R-project.org/: it is often is installed withEmacs but may need to be loaded, or even installed,separately).

Another is the Eclipse IDE with the Stat-ET plugin(https://projects.eclipse.org/projects/science.statet), and (onWindows only) Tinn-R(https://sourceforge.net/projects/tinn-r/).

People have also used LaTeX mode in a editor, as.Rd files arerather similar to LaTeX files.

Some R front-ends provide editing support for.Rd files, forexample RStudio (https://posit.co/).


Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

3 Tidying and profiling R code

R code which is worth preserving in a package and perhaps makingavailable for others to use is worth documenting, tidying up and perhapsoptimizing. The last two of these activities are the subject of thischapter.


Next:, Up:Tidying and profiling R code   [Contents][Index]

3.1 Tidying R code

R treats function code loaded from packages and code entered by usersdifferently. By default code entered by users has the source code storedinternally, and when the function is listed, the original source isreproduced. Loading code from a package (by default) discards thesource code, and the function listing is re-created from the parse treeof the function.

Normally keeping the source code is a good idea, and in particular itavoids comments being removed from the source. However, we can makeuse of the ability to re-create a function listing from its parse treeto produce a tidy version of the function, for example with consistentindentation and spaces around operators. If the original sourcedoes not follow the standard format this tidied version can be mucheasier to read.

We can subvert the keeping of source in two ways.

  1. The optionkeep.source can be set toFALSE before the codeis loaded into R.
  2. The stored source code can be removed by calling theremoveSource()function, for example by
    myfun <- removeSource(myfun)

In each case if we then list the function we will get the standardlayout.

Suppose we have a file of functionsmyfuns.R that we want totidy up. Create a filetidy.R containing

source("myfuns.R", keep.source = FALSE)dump(ls(all.names = TRUE), file = "new.myfuns.R")

and run R with this as the source file, for example byR--vanilla < tidy.R or by pasting into an R session. Then the filenew.myfuns.R will contain the functions in alphabetical order inthe standard layout. Warning: comments in your functions will be lost.

The standard format provides a good starting point for further tidying.Although the deparsing cannot do so, we recommend the consistent use ofthe preferred assignment operator ‘<-’ (rather than ‘=’) forassignment. Many package authors use a version of Emacs (on aUnix-alike or Windows) to edit R code, using the ESS[S] mode of theESS Emacs package.SeeR coding standards inR Internalsfor style options within the ESS[S] mode recommended for the source codeof R itself.


Next:, Previous:, Up:Tidying and profiling R code   [Contents][Index]

3.2 Profiling R code for speed

It is possible to profile R code on Windows and most127 Unix-alike versions ofR.

The commandRprof is used to control profiling, and its helppage can be consulted for full details. Profiling works by recording atfixed intervals128 (by default every20msecs) which line in which R function is being used, and recordingthe results in a file (defaultRprof.out in the workingdirectory). Then the functionsummaryRprof or the command-lineutilityR CMD RprofRprof.out can be used to summarize theactivity.

As an example, consider the following code (from Venables & Ripley,2002, pp. 225–6).

library(MASS); library(boot)storm.fm <- nls(Time ~ b*Viscosity/(Wt - c), stormer,                start = c(b=30.401, c=2.2183))st <- cbind(stormer, fit=fitted(storm.fm))storm.bf <- function(rs, i) {    st$Time <-  st$fit + rs[i]    tmp <- nls(Time ~ (b * Viscosity)/(Wt - c), st,               start = coef(storm.fm))    tmp$m$getAllPars()}rs <- scale(resid(storm.fm), scale = FALSE) # remove the meanRprof("boot.out")storm.boot <- boot(rs, storm.bf, R = 4999) # slow enough to profileRprof(NULL)

Having run this we can summarize the results by

R CMD Rprof boot.outEach sample represents 0.02 seconds.Total run time: 22.52 seconds.Total seconds: time spent in function and callees.Self seconds: time spent in function alone.
   %       total       %        self total    seconds     self    seconds    name 100.0     25.22       0.2      0.04     "boot"  99.8     25.18       0.6      0.16     "statistic"  96.3     24.30       4.0      1.02     "nls"  33.9      8.56       2.2      0.56     "<Anonymous>"  32.4      8.18       1.4      0.36     "eval"  31.8      8.02       1.4      0.34     ".Call"  28.6      7.22       0.0      0.00     "eval.parent"  28.5      7.18       0.3      0.08     "model.frame"  28.1      7.10       3.5      0.88     "model.frame.default"  17.4      4.38       0.7      0.18     "sapply"  15.0      3.78       3.2      0.80     "nlsModel"  12.5      3.16       1.8      0.46     "lapply"  12.3      3.10       2.7      0.68     "assign" ...
   %        self        %      total  self    seconds     total   seconds    name   5.7      1.44       7.5      1.88     "inherits"   4.0      1.02      96.3     24.30     "nls"   3.6      0.92       3.6      0.92     "$"   3.5      0.88      28.1      7.10     "model.frame.default"   3.2      0.80      15.0      3.78     "nlsModel"   2.8      0.70       9.8      2.46     "qr.coef"   2.7      0.68      12.3      3.10     "assign"   2.5      0.64       2.5      0.64     ".Fortran"   2.5      0.62       7.1      1.80     "qr.default"   2.2      0.56      33.9      8.56     "<Anonymous>"   2.1      0.54       5.9      1.48     "unlist"   2.1      0.52       7.9      2.00     "FUN"  ...

This often producessurprising results and can be used to identify bottlenecks or pieces ofR code that could benefit from being replaced by compiled code.

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

Profiling short runs can sometimes give misleading results. R fromtime to time performsgarbage collection to reclaim unusedmemory, and this takes an appreciable amount of time which profilingwill charge to whichever function happens to provoke it. It may beuseful to compare profiling code immediately after a call togc()with a profiling run without a preceding call togc.

More detailed analysis of the output can be achieved by the tools in theCRAN packagesproftools andprofr: inparticular these allow call graphs to be studied.


Next:, Previous:, Up:Tidying and profiling R code   [Contents][Index]

3.3 Profiling R code for memory use

Measuring memory use in R code is useful either when the code takesmore memory than is conveniently available or when memory allocation andcopying of objects is responsible for slow code. There are three ways toprofile memory use over time in R code. The second and third requireR to have been compiled with--enable-memory-profiling,which is not the default, but is currently used for the macOS andWindows binary distributions. All can be misleading, for differentreasons.

In understanding the memory profiles it is useful to know a little moreabout R’s memory allocation. Looking at the results ofgc()shows a division of memory intoVcells used to store the contentsof vectors andNcells used to store everything else, includingall the administrative overhead for vectors such as type and lengthinformation. In fact the vector contents are divided into twopools. Memory for small vectors (by default 128 bytes or less) isobtained in large chunks and then parcelled out by R; memory forlarger vectors is obtained directly from the operating system.

Some memory allocation is obvious in interpreted code, for example,

y <- x + 1

allocates memory for a new vectory. Other memory allocation isless obvious and occurs becauseR is forced to make good on itspromise of ‘call-by-value’ argument passing. When an argument ispassed to a function it is not immediately copied. Copying occurs (ifnecessary) only when the argument is modified. This can lead tosurprising memory use. For example, in the ‘survey’ package we have

print.svycoxph <- function (x, ...){    print(x$survey.design, varnames = FALSE, design.summaries = FALSE, ...)    x$call <- x$printcall    NextMethod()}

It may not be obvious that the assignment tox$call will causethe entire objectx to be copied. This copying to preserve thecall-by-value illusion is usually done by the internal C functionRf_duplicate.

The main reason that memory-use profiling is difficult is garbagecollection. Memory is allocated at well-defined times in an Rprogram, but is freed whenever the garbage collector happens to run.


Next:, Up:Profiling R code for memory use   [Contents][Index]

3.3.1 Memory statistics fromRprof

The sampling profilerRprof described in the previous section canbe given the optionmemory.profiling=TRUE. It then writes out thetotal R memory allocation in small vectors, large vectors, and conscells or nodes at each sampling interval. It also writes out the numberof calls to the internal functionRf_duplicate, which is called tocopy R objects.summaryRprof provides summaries of thisinformation. The main reason that this can be misleading is that thememory use is attributed to the function running at the end of thesampling interval. A second reason is that garbage collection can makethe amount of memory in use decrease, so a function appears to uselittle memory. Running undergctorture helps with both problems:it slows down the code to effectively increase the sampling frequencyand it makes each garbage collection release a smaller amount of memory.


Next:, Previous:, Up:Profiling R code for memory use   [Contents][Index]

3.3.2 Tracking memory allocations

The second method of memory profiling uses a memory-allocationprofiler,Rprofmem(), which writes out a stack trace to anoutput file every time a large vector is allocated (with auser-specified threshold for ‘large’) or a new page of memory isallocated for the R heap. Summary functions for this output are stillbeing designed.

Running the example from the previous section with

> Rprofmem("boot.memprof",threshold=1000)> storm.boot <- boot(rs, storm.bf, R = 4999)> Rprofmem(NULL)

shows that apart from some initial and final work inboot thereare no vector allocations over 1000 bytes.


Previous:, Up:Profiling R code for memory use   [Contents][Index]

3.3.3 Tracing copies of an object

The third method of memory profiling involves tracing copies made of aspecific (presumably large) R object. Callingtracemem on anobject marks it so that a message is printed to standard output whenthe object is copiedviaRf_duplicate or coercion to another type,or when a new object of the same size is created in arithmeticoperations. The main reason that this can be misleading is thatcopying of subsets or components of an object is not tracked. It maybe helpful to usetracemem on these components.

In the example above we can runtracemem on the data framest

> tracemem(st)[1] "<0x9abd5e0>"> storm.boot <- boot(rs, storm.bf, R = 4)memtrace[0x9abd5e0->0x92a6d08]: statistic bootmemtrace[0x92a6d08->0x92a6d80]: $<-.data.frame $<- statistic bootmemtrace[0x92a6d80->0x92a6df8]: $<-.data.frame $<- statistic bootmemtrace[0x9abd5e0->0x9271318]: statistic bootmemtrace[0x9271318->0x9271390]: $<-.data.frame $<- statistic bootmemtrace[0x9271390->0x9271408]: $<-.data.frame $<- statistic bootmemtrace[0x9abd5e0->0x914f558]: statistic bootmemtrace[0x914f558->0x914f5f8]: $<-.data.frame $<- statistic bootmemtrace[0x914f5f8->0x914f670]: $<-.data.frame $<- statistic bootmemtrace[0x9abd5e0->0x972cbf0]: statistic bootmemtrace[0x972cbf0->0x972cc68]: $<-.data.frame $<- statistic bootmemtrace[0x972cc68->0x972cd08]: $<-.data.frame $<- statistic bootmemtrace[0x9abd5e0->0x98ead98]: statistic bootmemtrace[0x98ead98->0x98eae10]: $<-.data.frame $<- statistic bootmemtrace[0x98eae10->0x98eae88]: $<-.data.frame $<- statistic boot

The object is duplicated fifteen times, three times for each of theR+1 calls tostorm.bf. This is surprising, since none of the duplications happen insidenls. Stepping throughstorm.bf in the debugger shows that all three happen in the line

st$Time <- st$fit + rs[i]

Data frames are slower than matrices and this is an example of why.Usingtracemem(st$Viscosity) does not reveal any additionalcopying.


Previous:, Up:Tidying and profiling R code   [Contents][Index]

3.4 Profiling compiled code

Profiling compiled code is highly system-specific, but this sectioncontains some hints gleaned from various R users. Some methods needto be different for a compiled executable and for dynamic/sharedlibraries/objects as used by R packages.

This chapter is based on reports from users and the information may notbe current.


Next:, Up:Profiling compiled code   [Contents][Index]

3.4.1 Profiling on Linux

Options include usingsprof for a shared object, andoprofile (seehttps://oprofile.sourceforge.io/news/)andperf (seehttps://perfwiki.github.io/) for anyexecutable or shared object. These seem less widely supplied than theyused to be. There is also ‘Google Performance Tools’, also known asgperftools orgoogle-perftools.

All of these work best when R and any packages have been built withdebugging symbols.

3.4.1.1perf

This seems the most widely distributed tool.Here is an example onx86_64 Linux using R 4.3.1 built withLTO.

At its simplest

The first report is

which shows which shared libraries (DSOs) the time was spent in.

perf annotate can be used on an application built with GCC and-ggdb: it interleaves disassembled and source code.

3.4.1.2oprofile andoperf

Theoprofile project has two modes of operation. Sinceversion 0.9.8 (August 2012), the preferred mode is to useoperf, so we discuss only that.

Let us look at theboot example from §3.2 onx86_64 Linuxusing R 4.3.1.

This can be run underoperf and analysed by commands like

operf R -f boot.Ropreportopreport -l /path/to/R_HOME/bin/exec/Ropreport -l /path/to/R_HOME/library/stats/src/stats.soopannotate --source /path/to/R_HOME/bin/exec/R

The first line had to be done as root.

The first report shows in which library (etc) the time was spent:

        CPU_CLK_UNHALT...|          samples|      %|        ------------------           278341 91.9947 R            18290  6.0450 libc.so.6             2277  0.7526 kallsyms             1426  0.4713 stats.so              739  0.2442 libRblas.so              554  0.1831 libz.so.1.2.11              373  0.1233 libm.so.6              352  0.1163 libtirpc.so.3.0.0              153  0.0506 ld-linux-x86-64.so.2               12  0.0040 methods.so

(kallsyms is the kernel.)

The rest of the output is voluminous, and only extracts are shown.

Most of the time within R is spent in

samples  %        image name symbol name52955    19.0574  R                        bcEval.lto_priv.016484     5.9322  R                        Rf_allocVector314224     5.1189  R                        Rf_findVarInFrame312581     4.5276  R                        CONS_NR8289      2.9830  R                        Rf_matchArgs_NR8034      2.8913  R                        Rf_cons7114      2.5602  R                        R_gc_internal.lto_priv.06552      2.3579  R                        Rf_eval5969      2.1481  R                        VECTOR_ELT5684      2.0456  R                        Rf_applyClosure5497      1.9783  R                        findVarLocInFrame.part.0.lto_priv.04827      1.7371  R                        Rf_mkPROMISE4609      1.6587  R                        Rf_install4317      1.5536  R                        Rf_findFun34035      1.4521  R                        getvar.lto_priv.03491      1.2563  R                        SETCAR3179      1.1441  R                        Rf_defineVar2892      1.0408  R                        duplicate1.lto_priv.0

and instats.so

samples  %        image name               symbol name285      24.4845  stats.so                 termsform284      24.3986  stats.so                 numeric_deriv213      18.2990  stats.so                 modelframe114       9.7938  stats.so                 nls_iter55        4.7251  stats.so                 ExtractVars47        4.0378  stats.so                 EncodeVars37        3.1787  stats.so                 getListElement32        2.7491  stats.so                 TrimRepeats25        2.1478  stats.so                 InstallVar20        1.7182  stats.so                 MatchVar20        1.7182  stats.so                 isZeroOne15        1.2887  stats.so                 ConvInfoMsg.isra.0

The profiling data is by default stored in sub-directoryoprofile_data of the current directory, which can be removed atthe end of the session.

3.4.1.3sprof

You can select shared objects to be profiled withsprof bysetting the environment variableLD_PROFILE. For example

% setenv LD_PROFILE /path/to/R_HOME/library/stats/libs/stats.so% R -f boot.R% sprof /path/to/R_HOME/library/stats/libs/stats.so \  /var/tmp/path/to/R_HOME/library/stats/libs/stats.so.profileFlat profile:Each sample counts as 0.01 seconds.  %   cumulative   self              self     total time   seconds   seconds    calls  us/call  us/call  name 76.19      0.32     0.32        0     0.00           numeric_deriv 16.67      0.39     0.07        0     0.00           nls_iter  7.14      0.42     0.03        0     0.00           getListElement... to clean up ...rm /var/tmp/path/to/R_HOME/library/stats/libs/stats.so.profile

It is possible that root access will be needed to create the directoriesused for the profile data.


Next:, Previous:, Up:Profiling compiled code   [Contents][Index]

3.4.2 Profiling on macOS

Developers have recommendedInstruments (part ofXcode,seehttps://help.apple.com/instruments/mac/current/), This had acommand-line version prior to macOS 12.


Previous:, Up:Profiling compiled code   [Contents][Index]

3.4.3 Profiling on Windows

Very Sleepy(https://github.com/VerySleepy/verysleepy) has been used on‘x86_64’ Windows. There wereproblems with accessing the debug information, but the best results whichincluded function names were obtained by attaching the profiler to anexistingRterm process, either via GUI or using/a:(PID obtained viaSys.getpid()).


Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

4 Debugging

This chapter covers the debugging of R extensions, starting with theways to get useful error information and moving on to how to deal witherrors that crash R.


Next:, Up:Debugging   [Contents][Index]

4.1 Browsing

Most of the R-level debugging facilities are based around thebuilt-in browser. This can be used directly by inserting a call tobrowser() into the code of a function (for example, usingfix(my_function) ). When code execution reaches that point inthe function, control returns to the R console with a special prompt.For example

> fix(summary.data.frame) ## insert browser() call after for() loop> summary(women)Called from: summary.data.frame(women)Browse[1]> ls() [1] "digits" "i"      "lbs"    "lw"     "maxsum" "ncw"    "nm"     "nr" [9] "nv"     "object" "sms"    "z"Browse[1]> maxsum[1] 7Browse[1]> c     height         weight Min.   :58.0   Min.   :115.0 1st Qu.:61.5   1st Qu.:124.5 Median :65.0   Median :135.0 Mean   :65.0   Mean   :136.7 3rd Qu.:68.5   3rd Qu.:148.0 Max.   :72.0   Max.   :164.0> rm(summary.data.frame)

At the browser prompt one can enter any R expression, so for examplels() lists the objects in the current frame, and entering thename of an object will129 print it. The following commands arealso accepted

  • n

    Enter ‘step-through’ mode. In this mode, hitting the return key (RET) executes thenext line of code (more precisely one line and any continuation lines).Typingc will continue to the end of the current context, e.g.to the end of the current loop or function.

  • c

    In normal mode, this quits the browser and continues execution, and justreturn works in the same way.cont is a synonym.

  • where

    This prints the call stack. For example

    > summary(women)Called from: summary.data.frame(women)Browse[1]> wherewhere 1: summary.data.frame(women)where 2: summary(women)Browse[1]>
  • Q

    Quit both the browser and the current expression, and return to thetop-level prompt.

Errors in code executed at the browser prompt will normally returncontrol to the browser prompt. Objects can be altered by assignment,and will keep their changed values when the browser is exited. Ifreally necessary, objects can be assigned to the workspace from thebrowser prompt (by using<<- if the name is not already inscope).


Next:, Previous:, Up:Debugging   [Contents][Index]

4.2 Debugging R code

Suppose your R program gives an error message. The first thing tofind out is what R was doing at the time of the error, and the mostuseful tool istraceback(). We suggest that this is run wheneverthe cause of the error is not immediately obvious. Errors are oftenreported to the R mailing lists as being in some package whentraceback() would show that the error was being reported by someother package or base R. Here is an example from the regressionsuite.

> success <- c(13,12,11,14,14,11,13,11,12)> failure <- c(0,0,0,0,0,0,0,2,2)> resp <- cbind(success, failure)> predictor <- c(0, 5^(0:7))> glm(resp ~ 0+predictor, family = binomial(link="log"))Error: no valid set of coefficients has been found: please supply starting values> traceback()3: stop("no valid set of coefficients has been found: please supply         starting values", call. = FALSE)2: glm.fit(x = X, y = Y, weights = weights, start = start, etastart = etastart,       mustart = mustart, offset = offset, family = family, control = control,       intercept = attr(mt, "intercept") > 0)1: glm(resp ~ 0 + predictor, family = binomial(link ="log"))

The calls to the active frames are given in reverse order (starting withthe innermost). So we see the error message comes from an explicitcheck inglm.fit. (traceback() shows you all the lines ofthe function calls, which can be limited by settingoption"deparse.max.lines".)

Sometimes the traceback will indicate that the error was detected insidecompiled code, for example (from?nls)

Error in nls(y ~ a + b * x, start = list(a = 0.12345, b = 0.54321), trace = TRUE) :        step factor 0.000488281 reduced below 'minFactor' of 0.000976563>  traceback()2: .Call(R_nls_iter, m, ctrl, trace)1: nls(y ~ a + b * x, start = list(a = 0.12345, b = 0.54321), trace = TRUE)

This will be the case if the innermost call is to.C,.Fortran,.Call,.External or.Internal, butas it is also possible for such code to evaluate R expressions, thisneed not be the innermost call, as in

> traceback()9: gm(a, b, x)8: .Call(R_numeric_deriv, expr, theta, rho, dir)7: numericDeriv(form[[3]], names(ind), env)6: getRHS()5: assign("rhs", getRHS(), envir = thisEnv)4: assign("resid", .swts * (lhs - assign("rhs", getRHS(), envir = thisEnv)),       envir = thisEnv)3: function (newPars)   {       setPars(newPars)       assign("resid", .swts * (lhs - assign("rhs", getRHS(), envir = thisEnv)),           envir = thisEnv)       assign("dev", sum(resid^2), envir = thisEnv)       assign("QR", qr(.swts * attr(rhs, "gradient")), envir = thisEnv)       return(QR$rank < min(dim(QR$qr)))   }(c(-0.00760232418963883, 1.00119632515036))2: .Call(R_nls_iter, m, ctrl, trace)1: nls(yeps ~ gm(a, b, x), start = list(a = 0.12345, b = 0.54321))

Occasionallytraceback() does not help, and this can be the caseif S4 method dispatch is involved. Consider the following example

> xyd <- new("xyloc", x=runif(20), y=runif(20))Error in as.environment(pkg) : no item called "package:S4nswv"on the search listError in initialize(value, ...) : S language method selection gotan error when called from internal dispatch for function 'initialize'> traceback()2: initialize(value, ...)1: new("xyloc", x = runif(20), y = runif(20))

which does not help much, as there is no call toas.environmentininitialize (and the note “called from internal dispatch”tells us so). In this case we searched the R sources for the quotedcall, which occurred in only one place,methods:::.asEnvironmentPackage. So now we knew where theerror was occurring. (This was an unusually opaque example.)

The error message

evaluation nested too deeply: infinite recursion / options(expressions=)?

can be hard to handle with the default value (5000). Unless you knowthat there actually is deep recursion going on, it can help to setsomething like

options(expressions=500)

and re-run the example showing the error.

Sometimes there is warning that clearly is the precursor to some latererror, but it is not obvious where it is coming from. Settingoptions(warn = 2) (which turns warnings into errors) can help here.

Once we have located the error, we have some choices. One way to proceedis to find out more about what was happening at the time of the crash bylooking apost-mortem dump. To do so, setoptions(error=dump.frames) and run the code again. Then invokedebugger() and explore the dump. Continuing our example:

> options(error = dump.frames)> glm(resp ~ 0 + predictor, family = binomial(link ="log"))Error: no valid set of coefficients has been found: please supply starting values

which is the same as before, but an object calledlast.dump hasappeared in the workspace. (Such objects can be large, so remove itwhen it is no longer needed.) We can examine this at a later time bycalling the functiondebugger.

> debugger()Message:  Error: no valid set of coefficients has been found: please supply starting valuesAvailable environments had calls:1: glm(resp ~ 0 + predictor, family = binomial(link = "log"))2: glm.fit(x = X, y = Y, weights = weights, start = start, etastart = etastart, mus3: stop("no valid set of coefficients has been found: please supply starting valuesEnter an environment number, or 0 to exit  Selection:

which gives the same sequence of calls astraceback, but inouter-first order and with only the first line of the call, truncated tothe current width. However, we can now examine in more detail what washappening at the time of the error. Selecting an environment opens thebrowser in that frame. So we select the function call which spawned theerror message, and explore some of the variables (and execute twofunction calls).

Enter an environment number, or 0 to exit  Selection: 2Browsing in the environment with call:   glm.fit(x = X, y = Y, weights = weights, start = start, etasCalled from: debugger.look(ind)Browse[1]> ls() [1] "aic"        "boundary"   "coefold"    "control"    "conv" [6] "dev"        "dev.resids" "devold"     "EMPTY"      "eta"[11] "etastart"   "family"     "fit"        "good"       "intercept"[16] "iter"       "linkinv"    "mu"         "mu.eta"     "mu.eta.val"[21] "mustart"    "n"          "ngoodobs"   "nobs"       "nvars"[26] "offset"     "start"      "valideta"   "validmu"    "variance"[31] "varmu"      "w"          "weights"    "x"          "xnames"[36] "y"          "ynames"     "z"Browse[1]> eta            1             2             3             4             5 0.000000e+00 -2.235357e-06 -1.117679e-05 -5.588393e-05 -2.794197e-04            6             7             8             9-1.397098e-03 -6.985492e-03 -3.492746e-02 -1.746373e-01Browse[1]> valideta(eta)[1] TRUEBrowse[1]> mu        1         2         3         4         5         6         7         81.0000000 0.9999978 0.9999888 0.9999441 0.9997206 0.9986039 0.9930389 0.9656755        90.8397616Browse[1]> validmu(mu)[1] FALSEBrowse[1]> cAvailable environments had calls:1: glm(resp ~ 0 + predictor, family = binomial(link = "log"))2: glm.fit(x = X, y = Y, weights = weights, start = start, etastart = etastart3: stop("no valid set of coefficients has been found: please supply starting vEnter an environment number, or 0 to exit  Selection: 0> rm(last.dump)

Becauselast.dump can be looked at later or even in another Rsession, post-mortem debugging is possible even for batch usage of R.We do need to arrange for the dump to be saved: this can be done eitherusing the command-line flag--save to save the workspace at theend of the run, orvia a setting such as

> options(error = quote({dump.frames(to.file=TRUE); q()}))

See the help ondump.frames for further options and a workedexample.

An alternative error action is to use the functionrecover():

> options(error = recover)> glm(resp ~ 0 + predictor, family = binomial(link = "log"))Error: no valid set of coefficients has been found: please supply starting valuesEnter a frame number, or 0 to exit1: glm(resp ~ 0 + predictor, family = binomial(link = "log"))2: glm.fit(x = X, y = Y, weights = weights, start = start, etastart = etastartSelection:

which is very similar todump.frames. However, we can examinethe state of the program directly, without dumping and re-loading thedump. As its help page says,recover can be routinely used asthe error action in place ofdump.calls anddump.frames,since it behaves likedump.frames in non-interactive use.

Post-mortem debugging is good for finding out exactly what went wrong,but not necessarily why. An alternative approach is to take a closerlook at what was happening just before the error, and a good way to dothat is to usedebug. This inserts a call to the browserat the beginning of the function, starting in step-through mode. So inour example we could use

> debug(glm.fit)> glm(resp ~ 0 + predictor, family = binomial(link ="log"))debugging in: glm.fit(x = X, y = Y, weights = weights, start = start, etastart = etastart,    mustart = mustart, offset = offset, family = family, control = control,    intercept = attr(mt, "intercept") > 0)debug: {## lists the whole functionBrowse[1]>debug: x <- as.matrix(x)...Browse[1]> start[1] -2.235357e-06debug: eta <- drop(x %*% start)Browse[1]> eta            1             2             3             4             5 0.000000e+00 -2.235357e-06 -1.117679e-05 -5.588393e-05 -2.794197e-04            6             7             8             9-1.397098e-03 -6.985492e-03 -3.492746e-02 -1.746373e-01Browse[1]>debug: mu <- linkinv(eta <- eta + offset)Browse[1]> mu        1         2         3         4         5         6         7         81.0000000 0.9999978 0.9999888 0.9999441 0.9997206 0.9986039 0.9930389 0.9656755        90.8397616

(The promptBrowse[1]> indicates that this is the first level ofbrowsing: it is possible to step into another function that is itselfbeing debugged or contains a call tobrowser().)

debug can be used for hidden functions and S3 methods bye.g.debug(stats:::predict.Arima). (It cannot be used for S4methods, but an alternative is given on the help page fordebug.)Sometimes you want to debug a function defined inside another function,e.g. the functionarimafn defined insidearima. To do so,setdebug on the outer function (herearima) andstep through it until the inner function has been defined. Thencalldebug on the inner function (and usec to get out ofstep-through mode in the outer function).

To remove debugging of a function, callundebug with the argumentpreviously given todebug; debugging otherwise lasts for the restof the R session (or until the function is edited or otherwisereplaced).

trace can be used to temporarily insert debugging code into afunction, for example to insert a call tobrowser() just beforethe point of the error. To return to our running example

## first get a numbered listing of the expressions of the function> page(as.list(body(glm.fit)), method="print")> trace(glm.fit, browser, at=22)Tracing function "glm.fit" in package "stats"[1] "glm.fit"> glm(resp ~ 0 + predictor, family = binomial(link ="log"))Tracing glm.fit(x = X, y = Y, weights = weights, start = start,   etastart = etastart,  .... step 22Called from: eval(expr, envir, enclos)Browse[1]> n## and single-step from here.> untrace(glm.fit)

For your own functions, it may be as easy to usefix to inserttemporary code, buttrace can help with functions in a namespace(as canfixInNamespace). Alternatively, usetrace(,edit=TRUE) to insert code visually.


Next:, Previous:, Up:Debugging   [Contents][Index]

4.3 Checking memory access

Errors in memory allocation and reading/writing outside arrays are verycommon causes of crashes (e.g., segfaults) on some machines. Oftenthe crash appears long after the invalid memory access: in particulardamage to the structures which R itself has allocated may only becomeapparent at the next garbage collection (or even at later garbagecollections after objects have been deleted).

Note that memory access errors may be seen with LAPACK, BLAS,OpenMP andJava-using packages: some at least of these seem to be intentional, andsome are related to passing characters to Fortran.

Some of these tools can detect mismatched allocation and deallocation.C++ programmers should note that memory allocated bynew [] mustbe freed bydelete [], other uses ofnew bydelete,and memory allocated bymalloc,calloc andreallocbyfree. Some platforms will tolerate mismatches (perhaps withmemory leaks) but others will segfault.


Next:, Up:Checking memory access   [Contents][Index]

4.3.1 Usinggctorture

We can help to detect memory problems in R objects earlier by runninggarbage collection as often as possible. This is achieved bygctorture(TRUE), which as described on its help page

Provokes garbage collection on (nearly) every memory allocation.Intended to ferret out memory protection bugs. Also makes R runvery slowly, unfortunately.

The reference to ‘memory protection’ is to missing C-level calls toPROTECT/UNPROTECT (seeHandling the effects of garbage collection) which ifmissing allow R objects to be garbage-collected when they are stillin use. But it can also help with other memory-related errors.

Normally running undergctorture(TRUE) will just produce a crashearlier in the R program, hopefully close to the actual cause. Seethe next section for how to decipher such crashes.

It is possible to run all the examples, tests and vignettes covered byR CMD check undergctorture(TRUE) by using the option--use-gct.

The functiongctorture2 provides more refined control over theGCtorture process. Its argumentsstep,wait andinhibit_release are documented on its help page. Environmentvariables can also be used at the start of the R session to turn onGC torture:R_GCTORTURE corresponds to thestep argument togctorture2,R_GCTORTURE_WAIT towait, andR_GCTORTURE_INHIBIT_RELEASE toinhibit_release.

If R is configured with--enable-strict-barrier then avariety of tests for the integrity of the write barrier are enabled. Inaddition tests to help detect protect issues are enabled:

R CMD check --use-gct can be set to usegctorture2(n) rather thangctorture(TRUE) by settingenvironment variable_R_CHECK_GCT_N_ to a positive integer valueto be used asn.

Used with a debugger and withgctorture orgctorture2 thismechanism can be helpful in isolating memory protect problems.


Next:, Previous:, Up:Checking memory access   [Contents][Index]

4.3.2 Using Valgrind

If you have access to Linux on a common CPU type or supported versionsof FreeBSD or Solaris130 you can usevalgrind(https://valgrind.org/, pronounced to rhyme with ‘tinned’) tocheck for possible problems. To run some examples undervalgrinduse something like

R -d valgrind --vanilla < mypkg-Ex.RR -d "valgrind --tool=memcheck --leak-check=full" --vanilla < mypkg-Ex.R

wheremypkg-Ex.R is a set of examples, e.g. the file created inmypkg.Rcheck byR CMD check. Occasionally this reportsmemory reads of ‘uninitialised values’ that are the result of compileroptimization, so can be worth checking under an unoptimized compile: formaximal information use a build with debugging symbols. We know therewill be some small memory leaks fromreadline and R itself —these are memory areas that are in use right up to the end of the Rsession. Expect this to run around 20x slower than withoutvalgrind, and in some cases much slower than that. Severalversions ofvalgrind were not happy with some optimized BLAS librariesthat useCPU-specific instructions so you may need to build aversion of R specifically to use withvalgrind.

On platforms wherevalgrind and its headers131are installed you can build a version of R with extra instrumentationto helpvalgrind detect errors in the use of memory allocatedfrom the R heap. Theconfigure option is--with-valgrind-instrumentation=level, wherelevelis 0, 1 or 2. Level 0 is the default and does not add anything. Level1 will detect some uses132 of uninitialised memory and has little impact on speed(compared to level 0). Level 2 will detect many other memory-usebugs133 but make R much slower when running undervalgrind. Using this in conjunction withgctorture can beeven more effective (and even slower).

An example ofvalgrind output is

==12539== Invalid read of size 4==12539==    at 0x1CDF6CBE: csc_compTr (Mutils.c:273)==12539==    by 0x1CE07E1E: tsc_transpose (dtCMatrix.c:25)==12539==    by 0x80A67A7: do_dotcall (dotcode.c:858)==12539==    by 0x80CACE2: Rf_eval (eval.c:400)==12539==    by 0x80CB5AF: R_execClosure (eval.c:658)==12539==    by 0x80CB98E: R_execMethod (eval.c:760)==12539==    by 0x1B93DEFA: R_standardGeneric (methods_list_dispatch.c:624)==12539==    by 0x810262E: do_standardGeneric (objects.c:1012)==12539==    by 0x80CAD23: Rf_eval (eval.c:403)==12539==    by 0x80CB2F0: Rf_applyClosure (eval.c:573)==12539==    by 0x80CADCC: Rf_eval (eval.c:414)==12539==    by 0x80CAA03: Rf_eval (eval.c:362)==12539==  Address 0x1C0D2EA8 is 280 bytes inside a block of size 1996 alloc'd==12539==    at 0x1B9008D1: malloc (vg_replace_malloc.c:149)==12539==    by 0x80F1B34: GetNewPage (memory.c:610)==12539==    by 0x80F7515: Rf_allocVector (memory.c:1915)...

This example is from an instrumented version of R, while trackingdown a bug in theMatrix package in 2006. The first lineindicates that R has tried to read 4 bytes from a memory address thatit does not have access to. This is followed by a C stack trace showingwhere the error occurred. Next is a description of the memory that wasaccessed. It is inside a block allocated bymalloc, called fromGetNewPage, that is, in the internal R heap. Since thismemory all belongs to R,valgrind would not (and did not)detect the problem in an uninstrumented build of R. In this examplethe stack trace was enough to isolate and fix the bug, which was intsc_transpose, and in this example running undergctorture() did not provide any additional information.

valgrind is good at spotting the use of uninitialized values:use option--track-origins=yes to show where these originatedfrom. What it cannot detect is the misuse of arrays allocated on thestack: this includes C automatic variables and some134Fortran arrays.

It is possible to run all the examples, tests and vignettes covered byR CMD check undervalgrind by using the option--use-valgrind. If you do this you will need to select thevalgrind options some other way, for example by having a~/.valgrindrc file containing

--leak-check=full--track-origins=yes

or setting the environment variableVALGRIND_OPTS. As from R4.2.0,--use-valgrind also usesvalgrind whenre-building the vignettes.

This section has described the use ofmemtest, the default(and most useful) ofvalgrind’s tools. There are othersdescribed in its documentation:helgrind can be useful forthreaded programs.


Next:, Previous:, Up:Checking memory access   [Contents][Index]

4.3.3 Using the Address Sanitizer

AddressSanitizer (‘ASan’) is a tool with similar aimsto the memory checker invalgrind. It is available withsuitable builds135 ofgcc andclang on common Linux and macOS platforms.Seehttps://clang.llvm.org/docs/UsersManual.html#controlling-code-generation,https://clang.llvm.org/docs/AddressSanitizer.html andhttps://github.com/google/sanitizers.

More thorough checks of C++ code are done if the C++ library has been‘annotated’: at the time of writing this applied tostd::vectorinlibc++ for use withclang and gives rise to‘container-overflow136reports.

It requires code to have been compiledand linked with-fsanitize=address and compiling with-fno-omit-frame-pointerwill give more legible reports. It has a runtime penalty of 2–3x,extended compilation times and uses substantially more memory, often1–2GB, at run time. On 64-bit platforms it reserves (but does notallocate) 16–20TB of virtual memory: restrictive shell settings cancause problems. It can be helpful to increase the stack size, forexample to 40MB.

By comparison withvalgrind,ASan candetect misuse of stack and global variables but not the use ofuninitialized memory.

Recent versions return symbolic addresses for the location of the errorprovidedllvm-symbolizer137 is on the path: if it is available but noton the path or has been renamed138, one can use an environment variable, e.g.

ASAN_SYMBOLIZER_PATH=/path/to/llvm-symbolizer

An alternative is to pipe the output throughasan_symbolize.py139 and perhapsthen (for compiled C++ code)c++filt. (On macOS, you may needto rundsymutil to get line-number reports.)

The simplest way to make use of this is to build a version of R withsomething like

CC="gcc -std=gnu99 -fsanitize=address"CFLAGS="-fno-omit-frame-pointer -g -O2 -Wall -pedantic -mtune=native"

which will ensure that thelibasan run-time library is compiledinto the R executable. However this check can be enabled on aper-package basis by using a~/.R/Makevars file like

CC = gcc -std=gnu99 -fsanitize=address -fno-omit-frame-pointerCXX = g++ -fsanitize=address -fno-omit-frame-pointerFC = gfortran -fsanitize=address

(Note that-fsanitize=address has to be part of the compilerspecification to ensure it is used for linking. These settings will notbe honoured by packages which ignore~/.R/Makevars.) It willbe necessary to build R with

MAIN_LDFLAGS = -fsanitize=address

to link the runtime libraries into the R executable if it was notspecified as part of ‘CC’ when R was built. (For some buildswithoutOpenMP,-pthread is also required.)

For options availablevia the environment variableASAN_OPTIONS seehttps://github.com/google/sanitizers/wiki/AddressSanitizerFlags.Withgcc additional control is availablevia the--param flag: see itsman page.

For more detailed information on an error, R can be run under adebugger with a breakpoint set before the address sanitizer report isproduced: forgdb orlldb you could use

break __asan_report_error

(Seehttps://github.com/google/sanitizers/wiki/AddressSanitizerAndDebugger.)

More recent versions140 added the flag-fsanitize-address-use-after-scope: seehttps://github.com/google/sanitizers/wiki/AddressSanitizerUseAfterScope.

One of the checks done byASan is thatmalloc/free and in C++new/delete andnew[]/delete[] are used consistently(rather than sayfree being used to deallocate memory allocated bynew[]). This matters on some systems but not all: unfortunatelyon some of those where it does not matter, system libraries141 are not consistent. Thecheck can be suppressed by including ‘alloc_dealloc_mismatch=0’ inASAN_OPTIONS.

ASan also checks system calls and sometimes reports can refer toproblems in the system software and not the package nor R. A coupleof reports have been of ‘heap-use-after-free’ errors in the X11libraries called from Tcl/Tk.

Apple provide a version of the address sanitizer in recent versions ofits C/C++ compiler. This will probably give messages about‘malloc: nano zone abandoned’ which are innocuous and can be suppressedby setting environment variableMallocNanoZone to0.It can be helpful to install debug symbols (INSTALL --dsym forthe package under test and particularly for reverse dependencies.


4.3.3.1 Using the Leak Sanitizer

Forx86_64 Linux there is a leak sanitizer, ‘LSan’: seehttps://github.com/google/sanitizers/wiki/AddressSanitizerLeakSanitizer.This is available on recent versions ofgcc andclang, andwhere available is compiled in as part ofASan.

One way to invoke this from anASan-enabled build is by the environmentvariable

However, this was made the default as from LLVMclang 3.5 andgcc 5.1.0.

WhenLSan is enabled, leaks give the process a failure error status (bydefault23). For an R package this means the R process,and as the parser retains some memory to the end of the process, if Ritself was built againstASan all runs will have a failure error status(which may include running R as part of building R itself).

To disable this, allocation-mismatch checking and some strict C++checking use

The leak sanitizer is not part ofASan in the Appleclang implementation.

LSan also has a ‘stand-alone’ mode where it is compiled in using-fsanitize=leak and avoids the run-time overhead ofASan.


Next:, Previous:, Up:Checking memory access   [Contents][Index]

4.3.4 Using the Undefined Behaviour Sanitizer

‘Undefined behaviour’ is where the language standard does not requireparticular behaviour from the compiler. Examples include division byzero (where for doubles R requires theISO/IEC 60559 behaviour but C/C++ do not), useof zero-length arrays, shifts too far for signed types (e.g.intx, y; y = x << 31;), out-of-range coercion, invalid C++ casts andmis-alignment. Not uncommon examples of out-of-range coercion in Rpackages are attempts to coerce aNaN or infinity to typeint orNA_INTEGER to an unsigned type such assize_t. Also common isy[x - 1] forgetting thatxmight beNA_INTEGER.

‘UBSanitizer’ is a tool for C/C++ source code selected by-fsanitize=undefined in suitable builds142ofclang and GCC. Its (main) runtime library is linked intoeach package’s DLL, so it is less often needed to be included inMAIN_LDFLAGS. Platforms supported byclang are listedathttps://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#supported-platforms:CRAN uses it for C/C++ with both GCC andclang on‘x86_64’ Linux: the two toolchains often highlight differentthings with more reports fromclang than GCC.

This sanitizer may be combined with the Address Sanitizer by-fsanitize=undefined,address (where both are supported, and wehave seen library conflicts forclang 17 and later).

Finer control of what is checked can be achieved by other options.

Forclang seehttps://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#ubsan-checks.The current set is (on a single line):

-fsanitize=alignment,bool,bounds,builtin,enum,float-cast-overflow,float-divide-by-zero,function,implicit-unsigned-integer-truncation,implicit-signed-integer-truncation,implicit-integer-sign-change,integer-divide-by-zero,nonnull-attribute,null,nullability-arg,nullability-assign,nullability-return,object-size,pointer-overflow,return,returns-nonnull-attribute,shift,signed-integer-overflow,unreachable,unsigned-integer-overflow,unsigned-shift-base,vla-bound,vptr

(plus the more specific versionsarray-bounsds,local-bounds,shift-base andshift-exponent), oruse something like

-fsanitize=undefined -fno-sanitize=float-divide-by-zero

where in recent versions-fno-sanitize=float-divide-by-zero is thedefault.

Optionsreturn andvptr apply only to C++: tousevptr its run-time library needs to be linked into the mainR executable by building the latter with something like

MAIN_LD="clang++ -fsanitize=undefined"

Optionfloat-divide-by-zero is undesirable for use with Rwhich allow such divisions as part ofIEC 60559arithmetic, and in versions ofclang since June 2019 it is nolonger part of-fsanitize=undefined.

There are also groups of optionsimplicit-integer-truncation,mplicit-integer-arithmetic-value-change,implicit-conversion,integer andnullability.

For GCC seehttps://gcc.gnu.org/onlinedocs/gcc/Instrumentation-Options.html(or the manual for your version of GCC, installed orviahttps://gcc.gnu.org/onlinedocs/: look for ‘ProgramInstrumentation Options’) for the options supported by GCC: versions 13.xsupported

-fsanitize=alignment,bool,bounds,builtin,enum,integer-divide-by-zero,nonnull-attribute,null,object-size,pointer-overflow,return,returns-nonnull-attribute,shift,signed-integer-overflow,unreachable,vla-bound,vptr

plus the more specific versionsshift-base andshift-exponent and non-default options

bounds-strict,float-cast-overflow,float-divide-by-zero

wherefloat-divide-by-zero is not desirable for R uses andbounds-strict is an extension ofbounds.

Other useful flags include

-no-fsanitize-recover

which causes the first report to be fatal (it always is for theunreachable andreturn suboptions). For more detailedinformation on where the runtime error occurs, using

setenv UBSAN_OPTIONS 'print_stacktrace=1'

will include a traceback in the report. Beyond that, R canbe run under a debugger with a breakpoint set before the sanitizerreport is produced: forgdb orlldb you could use

break __ubsan_handle_float_cast_overflowbreak __ubsan_handle_float_cast_overflow_abort

or similar (there are handlers for each type of undefined behaviour).

There are also the compiler flags-fcatch-undefined-behaviorand-ftrapv, said to be more reliable inclang thangcc.

For more details on the topic seehttps://blog.regehr.org/archives/213 andhttps://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html(which has 3 parts).

It may or may not be possible to build R itself with-fsanitize=undefined: problems have in the past been seen withOpenMP-using code withgcc but there has been successwith LLVMclang up to version 16.. However, problems have beenseen with LLVMclang 17 and later, including missing entry pointsand R builds hanging. What has succeeded is to useUBSAN just forthe package under test (and not in combination withASAN). To do so,check with an unaltered R, using a customMakevars filesomething like

CC = clang -fsanitize=undefined -fno-sanitize=float-divide-by-zero -fno-omit-frame-pointerCXX = clang++ -fsanitize=undefined -fno-sanitize=float-divide-by-zero -fno-omit-frame-pointer -frttiUBSAN_DIR = /path/to/LLVM18/lib/clang/18/lib/x86_64-unknown-linux-gnuSAN_LIBS = $(UBSAN_DIR)/libclang_rt.ubsan_standalone.a $(UBSAN_DIR)/libclang_rt.ubsan_standalone_cxx.a

which links theUBSAN libraries statically into the package-under-test’sDSO.It is also possible to use the dynamic libraryvia

SAN_LIBS = -L$(UBSAN_DIR) -Wl,-rpath,$(UBSAN_DIR) -lclang_rt.ubsan_standalone

providedUBSAN_DIR is added to the runtime library path (as shownor usingLD_LIBRARY_PATH).N.B.: The details, especiallythe paths used, have changed several times recently.

Apple provides a version of the undefined behaviour sanitizer in recentversions of its C/C++ compiler. R was built with Appleclang 16 withconfig.site containing

CC="clang -fsanitize=address,undefined"CXX="clang++ -fsanitize=address,undefined"

and passed its checks.


Next:, Previous:, Up:Checking memory access   [Contents][Index]

4.3.5 Other analyses with ‘clang’

Recent versions of LLVMclang on Linux have‘ThreadSanitizer’(https://github.com/google/sanitizers/wiki#threadsanitizer), a‘data race detector for C/C++ programs’, and ‘MemorySanitizer’(https://clang.llvm.org/docs/MemorySanitizer.html,https://github.com/google/sanitizers) for the detection ofuninitialized memory. Both are based on and provide similarfunctionality to tools invalgrind. The ThreadSanitizeris also available for Appleclang on macOS.

clang has a ‘Static Analyzer’ which can be run on the sourcefiles during compilation: seehttps://clang-analyzer.llvm.org/.


Next:, Previous:, Up:Checking memory access   [Contents][Index]

4.3.6 Other analyses with ‘gcc’

GCC 10 introduced a new flag-fanalyzer which does staticanalysis during compilation, currently for C code. It is regarded asexperimental and it may slow down computation considerably whenproblems are found (and use many GB of resident memory). There is someoverlap with problems detected by the Undefined Behaviour sanitizer, butsome issues are only reported by this tool and as it is a staticanalysis, it does not rely on code paths being exercised.

Seehttps://gcc.gnu.org/onlinedocs/gcc-10.1.0/gcc/Static-Analyzer-Options.html(or the documentation for your version ofgcc if later) andhttps://developers.redhat.com/blog/2020/03/26/static-analysis-in-gcc-10


Next:, Previous:, Up:Checking memory access   [Contents][Index]

4.3.7 Using ‘Dr. Memory’

‘Dr. Memory’ fromhttps://drmemory.org/ is a memory checker for(currently) Windows, Linux and macOS with similar aims tovalgrind. It works with unmodified executables143and detects memory access errors, uninitialized reads and memory leaks.


Previous:, Up:Checking memory access   [Contents][Index]

4.3.8 Fortran array bounds checking

Most of the Fortran compilers used with R allow code to be compiledwith checking of array bounds: for examplegfortran has option-fbounds-check. This will give an error when the upper orlower bound is exceeded, e.g.

At line 97 of file .../src/appl/dqrdc2.fFortran runtime error: Index '1' of dimension 1 of array 'x' above upper bound of 0

One does need to be aware that lazy programmers often specify Fortrandimensions as1 rather than* or a real bound and thesewill be reported (as may* dimensions)

It is easy to arrange to use this check on just the code in yourpackage: add to~/.R/Makevars something like (forgfortran)

FFLAGS = -g -O2 -mtune=native -fbounds-check

when you runR CMD check.

This may report errors with the way that Fortran character variables arepassed, particularly when Fortran subroutines are called from C code andcharacter lengths are not passed (seeFortran character strings).


Next:, Previous:, Up:Debugging   [Contents][Index]

4.4 Debugging compiled code

Sooner or later programmers will be faced with the need to debugcompiled code loaded into R. This section is geared to platformsusinggdb with code compiled bygcc, but similar thingsare possible with other debuggers such aslldb(https://lldb.llvm.org/, used on macOS) and Sun’sdbx:some debuggers have graphical front-ends available.

Consider first ‘crashes’, that is when R terminated unexpectedly withan illegal memory access (a ‘segfault’ or ‘bus error’), illegalinstruction or similar. Unix-alike versions of R use a signalhandler which aims to give some basic information. For example

 *** caught segfault ***address 0x20000028, cause 'memory not mapped'Traceback: 1: .identC(class1[[1]], class2) 2: possibleExtends(class(sloti), classi, ClassDef2 = getClassDef(classi,where = where)) 3: validObject(t(cu)) 4: stopifnot(validObject(cu <- as(tu, "dtCMatrix")), validObject(t(cu)),validObject(t(tu)))Possible actions:1: abort (with core dump)2: normal R exit3: exit R without saving workspace4: exit R saving workspaceSelection: 3

Since the R process may be damaged, the only really safe options arethe first or third. (Note that a core dump is only produced whereenabled: a common default in a shell is to limit its size to 0, therebydisabling it.)

A fairly common cause of such crashes is a package which uses.Cor.Fortran and writes beyond (at either end) one of thearguments it is passed. There is a good way to detect this: usingoptions(CBoundsCheck = TRUE) (which can be selectedviathe environment variableR_C_BOUNDS_CHECK=yes) changes the way.C and.Fortran work to check if the compiled code writesin the 64 bytes at either end of an argument.

Another cause of a ‘crash’ is to overrun the C stack. R tries totrack that in its own code, but it may happen in third-party compiledcode. For modern POSIX-compliant OSes R can safely catch that andreturn to the top-level prompt, so one gets something like

> .C("aaa")Error: segfault from C stack overflow>

However, C stack overflows are fatal under Windows and normally defeatattempts at debugging on that platform. Further, the size of the stackis set when R is compiled on Windows, whereas on POSIX OSes it can beset in the shell from which R is launched.

If you have a crash which gives a core dump you can use something like

gdb /path/to/R/bin/exec/R core.12345

to examine the core dump. If core dumps are disabled or to catch errorsthat do not generate a dump one can run R directly under a debuggerby for example

$ R -d gdb --vanilla...gdb> run

at which point R will run normally, and hopefully the debugger willcatch the error and return to its prompt. This can also be used tocatch infinite loops or interrupt very long-running code. For a simpleexample

> for(i in 1:1e7) x <- rnorm(100)[hit Ctrl-C]Program received signal SIGINT, Interrupt.0x00397682 in _int_free () from /lib/tls/libc.so.6(gdb) where#0  0x00397682 in _int_free () from /lib/tls/libc.so.6#1  0x00397eba in free () from /lib/tls/libc.so.6#2  0xb7cf2551 in R_gc_internal (size_needed=313)    at /users/ripley/R/svn/R-devel/src/main/memory.c:743#3  0xb7cf3617 in Rf_allocVector (type=13, length=626)    at /users/ripley/R/svn/R-devel/src/main/memory.c:1906#4  0xb7c3f6d3 in PutRNGstate ()    at /users/ripley/R/svn/R-devel/src/main/RNG.c:351#5  0xb7d6c0a5 in do_random2 (call=0x94bf7d4, op=0x92580e8, args=0x9698f98,    rho=0x9698f28) at /users/ripley/R/svn/R-devel/src/main/random.c:183...

In many cases it is possible to attach a debugger to a running process:this is helpful if an alternative front-end is in use or to investigatea task that seems to be taking far too long. This is done by somethinglike

gdb -ppid

wherepid is the id of the R executable or front-endprocess and can be found from within a running R process by callingSys.getpid() or from a process monitor. This stops the processso its state can be examined: usecontinue to resume execution.

Some “tricks” worth knowing follow:


Next:, Up:Debugging compiled code   [Contents][Index]

4.4.1 Finding entry points in dynamically loaded code

Under most compilation environments, compiled code dynamically loadedinto R cannot have breakpoints set within it until it is loaded. Touse a symbolic debugger on such dynamically loaded code underUnix-alikes use

  • Call the debugger on the R executable, for example byR -d gdb.
  • Start R.
  • At the R prompt, usedyn.load orlibrary to load yourshared object.
  • Send an interrupt signal. This will put you back to the debuggerprompt.
  • Set the breakpoints in your code.
  • Continue execution of R by typingsignal 0 and hitting return (RET).

Under Windows signals may not be able to be used, and if so the procedure ismore complicated. See the rw-FAQ.


Next:, Previous:, Up:Debugging compiled code   [Contents][Index]

4.4.2 Inspecting R objects when debugging

The key to inspecting R objects from compiled code is the functionRf_PrintValue(SEXPs) which uses the normal R printingmechanisms to print the R object pointed to bys, orR_PV(SEXPs) which will only print ‘objects’.

One way to make use ofRf_PrintValue is to insert suitable calls into the code to be debugged.

Another way is to callR_PV from the symbolic debugger.For example, fromgdb we can use

(gdb) p R_PV(ab)

using the objectab from the convolution example, if we haveplaced a suitable breakpoint in the convolution C code.

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

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

By setting a breakpoint atdo_get and typingget("DF") atthe R prompt, one can find out the address in memory ofDF, forexample

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

(Debugger output reformatted for better legibility).

UsingR_PV() one can “inspect” the values of the variouselements of theSEXP, for example,

(gdb) p R_PV($1->attrib)$names[1] "a" "b"$row.names[1] "1" "2" "3"$class[1] "data.frame"$3 = void

To find out where exactly the corresponding information is stored, oneneeds to go “deeper”:

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

Another alternative is theR_inspect function which shows thelow-level structure of the objects recursively (addresses differ fromthe above as this example is created on another machine):

(gdb) p R_inspect($1)@100954d18 19 VECSXP g0c2 [OBJ,NAM(2),ATT] (len=2, tl=0)  @100954d50 13 INTSXP g0c2 [NAM(2)] (len=3, tl=0) 1,2,3  @100954d88 13 INTSXP g0c2 [NAM(2)] (len=3, tl=0) 4,5,6ATTRIB:  @102a70140 02 LISTSXP g0c0 []    TAG: @10083c478 01 SYMSXP g0c0 [MARK,NAM(2),gp=0x4000] "names"    @100954dc0 16 STRSXP g0c2 [NAM(2)] (len=2, tl=0)      @10099df28 09 CHARSXP g0c1 [MARK,gp=0x21] "a"      @10095e518 09 CHARSXP g0c1 [MARK,gp=0x21] "b"    TAG: @100859e60 01 SYMSXP g0c0 [MARK,NAM(2),gp=0x4000] "row.names"    @102a6f868 13 INTSXP g0c1 [NAM(2)] (len=2, tl=1) -2147483648,-3    TAG: @10083c948 01 SYMSXP g0c0 [MARK,gp=0x4000] "class"    @102a6f838 16 STRSXP g0c1 [NAM(2)] (len=1, tl=1)      @1008c6d48 09 CHARSXP g0c2 [MARK,gp=0x21,ATT] "data.frame"

In general the representation of each object follows the format:

@<address> <type-nr> <type-name> <gc-info> [<flags>] ...

For a more fine-grained control over the depth of the recursionand the output of vectorsR_inspect3 takes additional two character()parameters: maximum depth and the maximal number of elements that willbe printed for scalar vectors. The defaults inR_inspect arecurrently -1 (no limit) and 5 respectively.


Previous:, Up:Debugging compiled code   [Contents][Index]

4.4.3 Debugging on macOS

To debug code in a package it is easiest to unpack it in a directory andinstall it with

R CMD INSTALL --dsympkgname

as macOS does not store debugging symbols in the.so file. (Itis not necessary to have R built with debugging symbols, althoughcompiling the package should be done including-g inCFLAGS /CXXFLAGS /FFLAGS /FCFLAGS asappropriate.)

Security measures may prevent running aCRAN binarydistribution of R underlldb or attaching this as adebugger(https://cran.r-project.org/bin/macosx/RMacOSX-FAQ.html#I-cannot-attach-debugger-to-R),although both were possible on High Sierra and are again from R4.2.0. This can also affect locally compiled builds, where attaching toan interactive R session under Big Sur or Monterey worked in 2022after giving administrator permissionvia a popup-up. (To debugin what Apple deems a non-interactive session, e.g. logged in remotely,seeman DevToolsSecurity.)

Debugging a local build of R on macOS can raise additional hurdles asenvironment variables such asDYLD_FALLBACK_LIBRARY_PATH are notusually passed through144 thelldb process, resulting in messageslike

R -d lldb...(lldb) runProcess 16828 launched: '/path/to/bin/exec/R' (x86_64)dyld: Library not loaded: libR.dylib  Referenced from: /path/to/bin/exec/R

A quick workaround is to symlink the dylibs underR_HOME/lib tosomewhere where they will be found such as the current workingdirectory. It would be possible to do as the distributiondoes145 anduseinstall_name_tool, but that would have to be done for allthe dylibs including those in packages.

It may be simplest to attach the debugger to a running process (seeabove). Specifically, run R and when it is at the prompt just beforea command that is to be debugged, at a terminal

ps -ef | grep exec/R# identify the PIDpid for the next command: it is the second itemlldb -ppid(lldb) continue

and then return to the R console.

For non-interactive use, one may needlldb --batch.


Previous:, Up:Debugging   [Contents][Index]

4.5 Using Link-time Optimization

Where supported,link time optimization provides a comprehensiveway to check the consistency of calls between Fortran files or between Cand Fortran. Use thisviaR CMD INSTALL --use-LTO (butthat does not apply if there is asrc/Makefile file or a Windowsanalogue).

To set up support on a Unix-alike,seeLink-Time Optimization inR Installation and Administration.On Linux using GCC without building R withLTO support,it should suffice to set

LTO_OPT = -fltoLTO_FC_OPT = -fltoAR = gcc-arNM = gcc-nm

in a personal (or site)Makevars file:SeeCustomizing package compilation inR Installation and Administrationfor more information.

For Windows, first edit fileetc/${R_ARCH}/Makeconf to giveLTO_OPT the value-flto or do so in a personal/siteMakevars file; see also filesrc/gnuwin32/README.compilation in the sources.

For example:

boot.f:61: warning: type of 'ddot' does not match original declaration [-Wlto-type-mismatch]        y(j,i)=ddot(p,x(j,1),n,b(1,j,i),1)crq.f:1023: note: return value type mismatch

where the package author forgot to declare

      double precision ddot      external ddot

inboot.f. That package had its own copy ofddot: todetect misuse of the one in R’s BLAS library would have needed Rconfigured with--enable-lto=check.

Further examples:

rkpk2.f:77:5: warning: type of 'dstup' does not match original declaration [-Wlto-type-mismatch]      *info, wk)rkpk1.f:2565:5: note: type mismatch in parameter 14       subroutine dstup (s, lds, nobs, nnull, qraux, jpvt, y, q, ldqr,rkpk1.f:2565:5: note: 'dstup' was previously declared here

where the fourteenth argumentdum was missing in the call.

reg.f:78:33: warning: type of 'dqrdc' does not match original declaration [-Wlto-type-mismatch]       call dqrdc (sr, nobs, nobs, nnull, wk, dum, dum, 0)dstup.f:20: note: 'dqrdc' was previously declared here       call dqrdc (s, lds, nobs, nnull, qraux, jpvt, work, 1)

dqrdc is a LINPACK routine from R,jpvt is an integerarray andwork is a double precision one sodum cannotmatch both. (If--enable-lto=check had been used thecomparison would have been with the definition in R.)

For Fortran files all in the package, most inconsistencies can bedetected by concatenating the Fortran files and compiling the result,sometimes with clearer diagnostics than provided byLTO. For our lasttwo examples this gives

all.f:2966:72:      *info, work1)                                                                        1Warning: Missing actual argument for argument 'dum' at (1)

and

all.f:1663:72:      *ipvtwk), wk(ikwk), wk(iwork1), wk(iwork2), info)                                                                        1Warning: Type mismatch in argument 'jpvt' at (1); passed REAL(8) to INTEGER(4)

On a Unix-alike for a package with asrc/Makefile file,LTO canbe enabled by including suitable flags in that file, for example

LTO = $(LTO_OPT)LTO_FC = $(LTO_FC_OPT)

and ensuring these are used for compilation, for example as part ofCFLAGS,CXXFLAGS orFCFLAGS. IfR CMDSHLIB is used for compilation, add--use-LTO to its call.

On Windows for a package with asrc/Makefile.ucrt orsrc/Makefile.win file which includes‘"${R_HOME}/etc${R_ARCH}/Makeconf"’, include

LTO = $(LTO_OPT)

or to always useLTO however R was built,

LTO = -flto

Next:API: entry points for C code, Previous:, Up:Writing R Extensions   [Contents][Index]

5 System and foreign language interfaces

Many of the functions described here have entry-point names with aRf_ prefix: if they are called from C code (but not C++ code asfrom R 4.5.0) that prefix can be omitted. Users are encouraged touse the prefix when writing new C code.


Next:, Up:System and foreign language interfaces   [Contents][Index]

5.1 Operating system access

Access to operating system functions isvia the R functionssystem andsystem2.The details will differ by platform (see the on-line help), and aboutall that can safely be assumed is that the first argument will be astringcommand that will be passed for execution (not necessarilyby a shell) and the second argument tosystem will beinternal which if true will collect the output of the commandinto an R character vector.

On POSIX-compliant OSes these commands pass a command-line to a shell:Windows is not POSIX-compliant and there is a separate functionshell to do so.

The functionsystem.timeis available for timing. Timing on child processes is only available onUnix-alikes, and may not be reliable there.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.2 Interface functions.C and.Fortran

These two functions provide an interface to compiled code that has beenlinked into R, either at build time orviadyn.load(seedyn.load anddyn.unload). They are primarily intended forcompiled C and Fortran code respectively, but the.C function canbe used with other languages which can generate C interfaces, forexample C++ (seeInterfacing C++ code).

The first argument to each function is a character string specifying thesymbol name as known146 to C orFortran, that is the function or subroutine name. (That the symbol isloaded can be tested by, for example,is.loaded("cg"). Use thename you pass to.C or.Fortran rather than the translatedsymbol name.)

There can be up to 65 further arguments giving R objects to be passedto compiled code. Normally these are copied before being passed in, andcopied again to an R list object when the compiled code returns. Ifthe arguments are given names, these are used as names for thecomponents in the returned list object (but not passed to the compiledcode).

The following table gives the mapping between the modes of R atomicvectors and the types of arguments to a C function or Fortransubroutine.

R storage modeC typeFortran type
logicalint *INTEGER
integerint *INTEGER
doubledouble *DOUBLE PRECISION
complexRcomplex *DOUBLE COMPLEX
characterchar **CHARACTER(255)
rawunsigned char *none

On all R platformsint andINTEGER are 32-bit. Codeported from S-PLUS (which useslong * forlogical andinteger) will not work on all 64-bit platforms (although it mayappear to work on some, including ‘x86_64’ Windows). Note alsothat if your compiled code is a mixture of C functions and Fortransubprograms the argument types must match as given in the table above.

C typeRcomplex is a structure withdouble membersr andi defined in the header fileR_ext/Complex.h.147 (On most platforms this is stored in a way compatiblewith the C99double complex type: however, it may not be possibleto passRcomplex to a C99 function expecting adoublecomplex argument. Nor need it be compatible with a C++complextype. Moreover, the compatibility can depend on the optimization levelset for the compiler.)

Only a single character string of fixed length can be passed to or fromFortran (the length is not passed), and the success of this iscompiler-dependent: its use was formally deprecated in 2019. Other Robjects can be passed to.C, but it is much better to use one ofthe other interfaces.

It is possible to pass numeric vectors of storage modedouble toC asfloat * or to Fortran asREAL by setting theattributeCsingle, most conveniently by using the R functionsas.single,single ormode. This is intended onlyto be used to aid interfacing existing C or Fortran code.

Logical values are sent as0 (FALSE),1(TRUE) orINT_MIN = -2147483648 (NA, but only ifNAOK is true), and the compiled code should return one of thesethree values. (Non-zero values other thanINT_MIN are mapped toTRUE.) Note that the use ofint * for Fortran logical isnot guaranteed to be portable (although people have gotten away with itfor many years): it is better to pass integers and convert to/fromFortran logical in a Fortran wrapper.

Unless formal argumentNAOK is true, all the other arguments arechecked for missing valuesNA and for theIEEE specialvaluesNaN,Inf and-Inf, and the presence of anyof these generates an error. If it is true, these values are passedunchecked.

ArgumentPACKAGE confines the search for the symbol name to aspecific shared object (or use"base" for code compiled intoR). Its use is highly desirable, as there is no way to avoid twopackage writers using the same symbol name, and such name clashes arenormally sufficient to cause R to crash. (If it is not present andthe call is from the body of a function defined in a package namespace,the shared object loaded by the first (if any)useDynLibdirective will be used.)

Note that the compiled code should not return anything except throughits arguments: C functions should be of typevoid and Fortransubprograms should be subroutines.

To fix ideas, let us consider a very simple example which convolves twofinite sequences. (This is hard to do fast in interpreted R code, buteasy in C code.) We could do this using.C by

void convolve(double *a, int *na, double *b, int *nb, double *ab){    int nab = *na + *nb - 1;    for(int i = 0; i < nab; i++)        ab[i] = 0.0;    for(int i = 0; i < *na; i++)        for(int j = 0; j < *nb; j++)            ab[i + j] += a[i] * b[j];}

called from R by

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

Note that we take care to coerce all the arguments to the correct Rstorage mode before calling.C; mistakes in matching the typescan lead to wrong results or hard-to-catch errors.

Special care is needed in handlingcharacter vector arguments inC (or C++). On entry the contents of the elements are duplicated andassigned to the elements of achar ** array, and on exit theelements of the C array are copied to create new elements of a charactervector. This means that the contents of the character strings of thechar ** array can be changed, including to\0 to shortenthe string, but the strings cannot be lengthened. It ispossible148 to allocate a new stringviaR_alloc and replace an entry in thechar ** array by thenew string. However, when character vectors are used other than in aread-only way, the.Call interface is much to be preferred.

Passing character strings to Fortran code needs even more care, isdeprecated and should be avoided where possible. Only the first elementof the character vector is passed in, as a fixed-length (255) characterarray. Up to 255 characters are passed back to a length-one charactervector. How well this works (or even if it works at all) depends on theC and Fortran compilers on each platform (including on their options).Often what is being passed to Fortran is one of a small set of possiblevalues (a factor in R terms) which could alternatively be passed asan integer code: similarly Fortran code that wants to generatediagnostic messages could pass an integer code to a C or R wrapperwhich would convert it to a character string.

It is possible to pass some R objects other than atomic vectorsvia.C, but this is only supported for historical compatibility: usethe.Call or.External interfaces for such objects. AnyC/C++ code that includesRinternals.h should be calledvia.Call or.External.

.Fortran is primarily intended for Fortran 77 code, and longprecedes any support for ‘modern’ Fortran. Nowadays implementations ofFortran support the Fortran 2003 moduleiso_c_binding, a betterway to interface modern Fortran code to R is to use.C andwrite a C interface usinguse iso_c_binding.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.3dyn.load anddyn.unload

Compiled code to be used with R is loaded as a shared object(Unix-alikes including macOS, seeCreating shared objects for moreinformation) or DLL (Windows).

The shared object/DLL is loaded bydyn.load and unloaded bydyn.unload. Unloading is not normally necessary and is not safein general, but it is needed to allow the DLL to be re-built on someplatforms, including Windows. Unloading a DLL and then re-loading a DLLof the same name may not work: Solaris used the first version loaded. ADLL that registers C finalizers, but fails to unregister them whenunloaded, may cause R to crash after unloading.

The first argument to both functions is a character string giving thepath to the object. Programmers should not assume a specific fileextension for the object/DLL (such as.so) but use a constructionlike

file.path(path1, path2, paste0("mylib", .Platform$dynlib.ext))

for platform independence. On Unix-alike systems the path supplied todyn.load can be an absolute path, one relative to the currentdirectory or, if it starts with ‘~’, relative to the user’s homedirectory.

Loading is most often done automatically based on theuseDynLib()declaration in theNAMESPACE file, but may be doneexplicitlyvia a call tolibrary.dynam.This has the form

library.dynam("libname", package, lib.loc)

wherelibname is the object/DLL namewith the extensionomitted. Note that the first argument,chname, shouldnot bepackage since this will not work if the packageis installed under another name.

Under some Unix-alike systems there is a choice of how the symbols areresolved when the object is loaded, governed by the argumentslocal andnow. Only use these if really necessary: inparticular usingnow=FALSE and then calling an unresolved symbolwill terminate R unceremoniously.

R provides a way of executing some code automatically when a object/DLLis either loaded or unloaded. This can be used, for example, toregister native routines with R’s dynamic symbol mechanism, initializesome data in the native code, or initialize a third party library. Onloading a DLL, R will look for a routine within that DLL namedR_init_lib wherelib is the name of the DLL file withthe extension removed. For example, in the command

library.dynam("mylib", package, lib.loc)

R looks for the symbol namedR_init_mylib. Similarly, whenunloading the object, R looks for a routine namedR_unload_lib, e.g.,R_unload_mylib. In either case,if the routine is present, R will invoke it and pass it a singleargument describing the DLL. This is a value of typeDllInfowhich is defined in theRdynload.h file in theR_extdirectory.

Note that there are some implicit restrictions on this mechanism as thebasename of the DLL needs to be both a valid file name and valid as partof a C entry point (e.g. it cannot contain ‘.’): for portablecode it is best to confine DLL names to beASCII alphanumericplus underscore. If entry pointR_init_lib is not found itis also looked for with ‘.’ replaced by ‘_’.

The following example shows templates for the initialization andunload routines for themylib DLL.

#include <R_ext/Rdynload.h>voidR_init_mylib(DllInfo *info){  /* Register routines,     allocate resources. */}voidR_unload_mylib(DllInfo *info){  /* Release resources. */}

If a shared object/DLL is loaded more than once the most recent versionis used.149 More generally, if the same symbol nameappears in several shared objects, the most recently loaded occurrenceis used. ThePACKAGE argument and registration (see the nextsection) provide good ways to avoid any ambiguity in which occurrence ismeant.

On Unix-alikes the paths used to resolve dynamically-linked dependentlibraries are fixed (for security reasons) when the process is launched,sodyn.load will only look for such libraries in the locationsset by theR shell script (viaetc/ldpaths) and inthe OS-specific defaults.

Windows allows more control (and less security) over where dependentDLLs are looked for. On all versions this includes thePATHenvironment variable, but with lowest priority: note that it does notinclude the directory from which the DLL was loaded. It is possible toadd a single path with quite high priorityvia theDLLpathargument todyn.load. This is (by default) used bylibrary.dynam to include the package’slibs/x64 directory (onIntel) in the DLL search path.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.4 Registering native routines

By ‘native’ routine, we mean an entry point in compiled code.

In calls to.C,.Call,.Fortran and.External, R must locate the specified native routine bylooking in the appropriate shared object/DLL. By default, R uses theoperating-system-specific dynamic loader to lookup the symbol inall150 loaded DLLs and the R executableor libraries it is linked to. Alternatively, the author of the DLL canexplicitly register routines with R and use a single,platform-independent mechanism for finding the routines in the DLL. Onecan use this registration mechanism to provide additional informationabout a routine, including the number and type of the arguments, andalso make it available to R programmers under a different name.

Registering routines has two main advantages: it provides afaster151 way tofind the address of the entry pointvia tables stored in the DLLat compilation time, and it provides a run-time check that the entrypoint is called with the right number of arguments and, optionally, theright argument types.

To register routines with R, one calls the C routineR_registerRoutines. This is typically done when the DLL is firstloaded within the initialization routineR_init_dll namedescribed indyn.load anddyn.unload.R_registerRoutinestakes 5 arguments. The first is theDllInfo object passed byR to the initialization routine. This is where R stores theinformation about the methods. The remaining 4 arguments are arraysdescribing the routines for each of the 4 different interfaces:.C,.Call,.Fortran and.External. Eachargument is aNULL-terminated array of the element types given inthe following table:

.CR_CMethodDef
.CallR_CallMethodDef
.FortranR_FortranMethodDef
.ExternalR_ExternalMethodDef

Currently, theR_ExternalMethodDef type is the same asR_CallMethodDef type and contains fields for the name of theroutine by which it can be accessed in R, a pointer to the actualnative symbol (i.e., the routine itself), and the number of argumentsthe routine expects to be passed from R. For example, if we had aroutine namedmyCall defined as

SEXP myCall(SEXP a, SEXP b, SEXP c);

we would describe this as

static const R_CallMethodDef callMethods[]  = {  {"myCall", (DL_FUNC) &myCall, 3},  {NULL, NULL, 0}};

along with any other routines for the.Call interface. Forroutines with a variable number of arguments invokedvia the.External interface, one specifies-1 for the number ofarguments which tells R not to check the actual number passed.

Routines for use with the.C and.Fortran interfaces aredescribed with similar data structures, which have one optionaladditional field for describing the type of each argument. Ifspecified, this field should be an array with theSEXP typesdescribing the expected type of each argument of the routine.(Technically, the elements of the types array are of typeR_NativePrimitiveArgType which is just an unsigned integer.)The R types and corresponding type identifiers are provided in thefollowing table:

numericREALSXP
integerINTSXP
logicalLGLSXP
singleSINGLESXP
characterSTRSXP
listVECSXP

Consider a C routine,myC, declared as

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

We would register it as

static R_NativePrimitiveArgType myC_type[] = {    REALSXP, INTSXP, STRSXP, LGLSXP};static const R_CMethodDef cMethods[] = {   {"myC", (DL_FUNC) &myC, 4, myC_type},   {NULL, NULL, 0, NULL}};

If registering types, check carefully that the number of types matchesthe number of arguments: as the type array (heremyC_type) ispassed as a pointer in C, the registration mechanism cannot check thisfor you.

Note that.Fortran entry points are mapped to lowercase, soregistration should use lowercase only.

Having created the arrays describing each routine, the last step is toactually register them with R. We do this by callingR_registerRoutines. For example, if we have the descriptionsabove for the routines accessed by the.C and.Callwe would use the following code:

voidR_init_myLib(DllInfo *info){   R_registerRoutines(info, cMethods, callMethods, NULL, NULL);}

This routine will be invoked when R loads the shared object/DLL namedmyLib. The last two arguments in the call toR_registerRoutines are for the routines accessed by.Fortran and.External interfaces. In our example, theseare given asNULL since we have no routines of these types.

When R unloads a shared object/DLL, its registrations are removed.There is no other facility for unregistering a symbol.

Examples of registering routines can be found in the different packagesin the R source tree (e.g.,stats andgraphics). Also,there is a brief, high-level introduction inR News (volume 1/3,September 2001, pages 20–23,https://www.r-project.org/doc/Rnews/Rnews_2001-3.pdf).

Once routines are registered, they can be referred to as R objects ifthis is arranged in theuseDynLib call in the package’sNAMESPACE file (seeuseDynLib). So for example thestats package has

# Refer to all C/Fortran routines by their name prefixed by C_useDynLib(stats, .registration = TRUE, .fixes = "C_")

in itsNAMESPACE file, and thenansari.test’s defaultmethods can contain

        pansari <- function(q, m, n)            .C(C_pansari, as.integer(length(q)), p = as.double(q),                as.integer(m), as.integer(n))$p

This avoids the overhead of looking up an entry point each time it isused, and ensures that the entry point in the package is the one used(without aPACKAGE = "pkg" argument).

R_init_ routines are often of the form

void attribute_visible R_init_mypkg(DllInfo *dll){    R_registerRoutines(dll, CEntries, CallEntries, FortEntries,                       ExternalEntries);    R_useDynamicSymbols(dll, FALSE);    R_forceSymbols(dll, TRUE);...}

TheR_useDynamicSymbols call says the DLL is not to be searchedfor entry points specified by character strings so.C etc callswill only find registered symbols: theR_forceSymbols call onlyallows.C etc calls which specify entry points by R objectssuch asC_pansari (and not by character strings). Each providessome protection against accidentally finding your entry points whenpeople supply a character string without a package, and avoids slowingdown such searches. (For the visibility attribute seeControlling visibility.)

In more detail, if a packagemypkg contains entry pointsreg andunreg and the first is registered as a 0-argument.Call routine, we could use (from code in the package)

.Call("reg").Call("unreg")

Without or with registration, these will both work. IfR_init_mypkg callsR_useDynamicSymbols(dll, FALSE), onlythe first will work. If in addition to registration theNAMESPACE file contains

useDynLib(mypkg, .registration = TRUE, .fixes = "C_")

then we can call.Call(C_reg). Finally, ifR_init_mypkgalso callsR_forceSymbols(dll, TRUE), only.Call(C_reg)will work (and not.Call("reg")). This is usually what we want:it ensures that all of our own.Call calls go directly to theintended code in our package and that no one else accidentally finds ourentry points. (Should someone need to call our code from outside thepackage, for example for debugging, they can use.Call(mypkg:::C_reg).)


Next:, Up:Registering native routines   [Contents][Index]

5.4.1 Speed considerations

Sometimes registering native routines or using aPACKAGE argumentcan make a large difference. The results can depend quite markedly onthe OS (and even if it is 32- or 64-bit), on the version of R andwhat else is loaded into R at the time.

To fix ideas, first considerx86_64 OS 10.7 and R 2.15.2. Asimple.Call function might be

foo <- function(x) .Call("foo", x)

with C code

#include <Rinternals.h>SEXP foo(SEXP x){    return x;}

If we compile with byR CMD SHLIB foo.c, load the code bydyn.load("foo.so") and runfoo(pi) it took around 22microseconds (us). Specifying the DLL by

foo2 <- function(x) .Call("foo", x, PACKAGE = "foo")

reduced the time to 1.7 us.

Now consider making these functions part of a package whoseNAMESPACE file usesuseDynlib(foo). This immediatelyreduces the running time as"foo" will be preferentially lookedforfoo.dll. Without specifyingPACKAGE it took about 5us (it needs to fathom out the appropriate DLL each time it is invokedbut it does not need to search all DLLs), and with thePACKAGEargument it is again about 1.7 us.

Next suppose the package has registered the native routinefoo.Thenfoo() still has to find the appropriate DLL but can get tothe entry point in the DLL faster, in about 4.2 us. Andfoo2()now takes about 1 us. If we register the symbols in theNAMESPACE file and use

foo3 <- function(x) .Call(C_foo, x)

then the address for the native routine is looked up just once when thepackage is loaded, andfoo3(pi) takes about 0.8 us.

Versions using.C() rather than.Call() took about 0.2 uslonger.

These are all quite small differences, but C routines are not uncommonlyinvoked millions of times for run times of a few microseconds each, andthose doing such things may wish to be aware of the differences.

On Linux and Solaris there is a smaller overhead in looking upsymbols.

Symbol lookup on Windows used to be far slower, so R maintains asmall cache. If the cache is currently empty enough that the symbol canbe stored in the cache then the performance is similar to Linux andSolaris: if not it may be slower. R’s own code always usesregistered symbols and so these never contribute to the cache: howevermany other packages do rely on symbol lookup.

In more recent versions of R all the standard packages registernative symbols and do not allow symbol search, so in a new sessionfoo() can only look infoo.so and may be as fast asfoo2(). This will no longer apply when many contributed packagesare loaded, and generally those last loaded are searched first. Forexample, consider R 3.3.2 on x86_64 Linux. In an empty R session,bothfoo() andfoo2() took about 0.75 us; however afterpackagesigraph andspatstat had been loaded (whichloaded another 12 DLLs),foo() took 3.6 us butfoo2()still took about 0.80 us. Using registration in a package reduced thisto 0.55 us andfoo3() took 0.40 us, times which were unchangedwhen further packages were loaded.


Next:, Previous:, Up:Registering native routines   [Contents][Index]

5.4.2 Example: converting a package to use registration

Thesplines package was converted to use symbol registration in2001, but we can use it as an example152 of what needs to be done for a small package.

  • Find the relevant entry points.This is somewhat OS-specific, but something like the following should bepossible at the OS command-line
    nm -g /path/to/splines.so | grep " T "0000000000002670 T _spline_basis0000000000001ec0 T _spline_value

    This indicates that there are two relevant entry points. (They may ormay not have a leading underscore, as here. Fortran entry points willhave a trailing underscore on all current platforms.) Check in the Rcode that they are called by the package and how: in this case they areused by.Call.

    Alternatively, examine the package’s R code for all.C,.Fortran,.Call and.External calls.

  • Construct the registration table. First write skeleton registrationcode, conventionally in filesrc/init.c (or at the end of theonly C source file in the package: if included in a C++ file the‘R_init’ function would need to be declaredextern "C"):
    #include <stdlib.h> // for NULL#include <R_ext/Rdynload.h>#define CALLDEF(name, n)  {#name, (DL_FUNC) &name, n}static const R_CallMethodDef R_CallDef[] = {   CALLDEF(spline_basis, ?),   CALLDEF(spline_value, ?),   {NULL, NULL, 0}};void R_init_splines(DllInfo *dll){    R_registerRoutines(dll, NULL, R_CallDef, NULL, NULL);}

    and then replace the? in the skeleton with the actual numbers ofarguments. You will need to add declarations (also known as‘prototypes’) of the functions unless appending to the only C sourcefile. Some packages will already have these in a header file, or youcould create one and include it ininit.c, for examplesplines.h containing

    #include <Rinternals.h> // for SEXPextern SEXP spline_basis(SEXP knots, SEXP order, SEXP xvals, SEXP derivs);extern SEXP spline_value(SEXP knots, SEXP coeff, SEXP order, SEXP x, SEXP deriv);

    Tools are available to extract declarations, at least for C and C++code: see the help file forpackage_native_routine_registration_skeleton in packagetools. Here we could have used

    cproto -I/path/to/R/include -e splines.c

    For examples of registering other types of calls, see packagesgraphics andstats. In particular, when registering entrypoints for.Fortran one needs declarations as if called from C,such as

    #include <R_ext/RS.h>void F77_NAME(supsmu)(int *n, double *x, double *y,                      double *w, int *iper, double *span, double *alpha,                      double *smo, double *sc, double *edf);

    gfortran 8.4, 9.2 and later can help generate such prototypeswith its flag-fc-prototypes-external (although one will needto replace the hard-coded trailing underscore with theF77_NAMEmacro).

    One can get away with inaccurate argument lists in the declarations: itis easy to specify the arguments for.Call (allSEXP) and.External (oneSEXP) and as the arguments for.Cand.Fortran are all pointers, specifying them asvoid *suffices. (For most platforms one can omit all the arguments, althoughlink-time optimization will warn, as will compilers set up to warn onstrict prototypes – and C23 requires correct arguments.)

    Using-fc-prototypes-external will give a prototype usingint_least32_t *lgl for FortranLOGICAL LGL, but this isnot portable and traditionally it has been assumed that the C/C++equivalent wasint *lgl. If adding a declaration just toregister a.Fortran call, the most portable version isvoid*lgl.

  • (Optional but highly recommended.) Restrict.Call etc to use thesymbols you chose to register by editingsrc/init.c to contain
    void R_init_splines(DllInfo *dll){    R_registerRoutines(dll, NULL, R_CallDef, NULL, NULL);    R_useDynamicSymbols(dll, FALSE);}

A skeleton for the steps so far can be made usingpackage_native_routine_registration_skeleton in packagetools. This will optionally create declarations based on theusage in the R code.

The remaining steps are optional but recommended.

  • Edit theNAMESPACE file to create R objects for the registeredsymbols:
    useDynLib(splines, .registration = TRUE, .fixes = "C_")
  • Find all the relevant calls in the R code and edit them to use theR objects. This entailed changing the lines
    temp <- .Call("spline_basis", knots, ord, x, derivs, PACKAGE = "splines")y[accept] <- .Call("spline_value", knots, coeff, ord, x[accept], deriv, PACKAGE = "splines")y = .Call("spline_value", knots, coef(object), ord, x, deriv, PACKAGE = "splines")

    to

    temp <- .Call(C_spline_basis, knots, ord, x, derivs)y[accept] <- .Call(C_spline_value, knots, coeff, ord, x[accept], deriv)y = .Call(C_spline_value, knots, coef(object), ord, x, deriv)

    Check that there is noexportPattern directive whichunintentionally exports the newly created R objects.

  • Restrict.Call to use the R symbols by editingsrc/init.c to contain
    void R_init_splines(DllInfo *dll){    R_registerRoutines(dll, NULL, R_CallDef, NULL, NULL);    R_useDynamicSymbols(dll, FALSE);    R_forceSymbols(dll, TRUE);}
  • Consider visibility. On some OSes we can hide entry points from theloader, which precludes any possible name clashes and calling themaccidentally (usually with incorrect arguments and crashing the Rprocess). If we repeat the first step we now see
    nm -g /path/to/splines.so | grep " T "0000000000002e00 T _R_init_splines00000000000025e0 T _spline_basis0000000000001e20 T _spline_value

    If there were any entry points not intended to be used by the package weshould try to avoid exporting them, for example by making themstatic. Now that the two relevant entry points are only accessedvia the registration table, we can hide them. There are two waysto do so on some153 Unix-alikes. We can hide individual entry pointsvia

    #include <R_ext/Visibility.h>SEXP attribute_hiddenspline_basis(SEXP knots, SEXP order, SEXP xvals, SEXP derivs)...SEXP attribute_hiddenspline_value(SEXP knots, SEXP coeff, SEXP order, SEXP x, SEXP deriv)...

    Alternatively, we can change the default visibility for all C symbols byincluding

    PKG_CFLAGS = $(C_VISIBILITY)

    insrc/Makevars, and then we need to allow registration bydeclaringR_init_splines to be visible:

    #include <R_ext/Visibility.h>void attribute_visibleR_init_splines(DllInfo *dll)...

    SeeControlling visibility for more details, including using Fortrancode and ways to restrict visibility on Windows.

  • We end up with a filesrc/init.c containing
    #include <stdlib.h>#include <R_ext/Rdynload.h>#include <R_ext/Visibility.h>  // optional#include "splines.h"#define CALLDEF(name, n)  {#name, (DL_FUNC) &name, n}static const R_CallMethodDef R_CallDef[] = {    CALLDEF(spline_basis, 4),    CALLDEF(spline_value, 5),    {NULL, NULL, 0}};voidattribute_visible  // optionalR_init_splines(DllInfo *dll){    R_registerRoutines(dll, NULL, R_CallDef, NULL, NULL);    R_useDynamicSymbols(dll, FALSE);    R_forceSymbols(dll, TRUE);}

Previous:, Up:Registering native routines   [Contents][Index]

5.4.3 Linking to native routines in other packages

In addition to registering C routines to be called by R, it can attimes be useful for one package to make some of its C routines availableto be called by C code in another package. The interface consists oftwo routines declared in headerR_ext/Rdynload.h as

void R_RegisterCCallable(const char *package, const char *name,                         DL_FUNC fptr);DL_FUNC R_GetCCallable(const char *package, const char *name);

A packagepackA that wants to make a C routinemyCfunavailable to C code in other packages would include the call

R_RegisterCCallable("packA", "myCfun", myCfun);

in its initialization functionR_init_packA. A packagepackB that wants to use this routine would retrieve the functionpointer with a call of the form

p_myCfun = R_GetCCallable("packA", "myCfun");

As the typeDL_FUNC is only appropriate for functions with noarguments, other users will need to cast to an appropriate type. Forexample

typedef SEXP (*na_omit_xts_func) (SEXP x);...  na_omit_xts_func fun = (na_omit_xts_func) R_GetCCallable("xts", "na_omit_xts");  return fun(x);

The author ofpackB is responsible for ensuring thatp_myCfun has an appropriate declaration. In the future R mayprovide some automated tools to simplify exporting larger numbers ofroutines.

A package that wishes to make use of header files in other packagesneeds to declare them as a comma-separated list in the field‘LinkingTo’ in theDESCRIPTION file. This then arrangesfor theinclude directories in the installed linked-to packagesto be added to the include paths for C and C++ code.

It must specify154Imports’ or ‘Depends’ of those packages, for they have to beloaded155 prior to this one(so the path to their compiled code has been registered).

CRAN examples of the use of this mechanism includecoxmelinking tobdsmatrix andxts linking tozoo.

NB: this mechanism is fragile, as changes to the interfaceprovided bypackA have to be recognised bypackB. Theconsequences of not doing so have included serious corruption to thememory pool of the R session. EitherpackB has to depend onthe exact version ofpackA or there needs to be a mechanism forpackB to test at runtime the version ofpackA it is linkedto matches that it was compiled against.

On rare occasions in can be useful for C code in one package todynamically look up the address in another package. This can be doneusingR_FindSymbol:

DL_FUNC R_FindSymbol(char const *name, char const *pkg,                     R_RegisteredNativeSymbol *symbol);

Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.5 Creating shared objects

Shared objects for loading into R can be created usingR CMDSHLIB. This accepts as arguments a list of files which must be objectfiles (with extension.o) or sources for C, C++, Fortran,Objective C or Objective C++ (with extensions.c,.cc or.cpp,.f (fixed-form Fortran),.f90 or.f95(free-form),.m, and.mm or.M, respectively), orcommands to be passed to the linker. SeeR CMD SHLIB --help (orthe R help forSHLIB) for usage information. Note that filesintended for the Fortran pre-processor with extension.F are notaccepted.

If compiling the source files does not work “out of the box”, you canspecify additional flags by setting some of the variablesPKG_CPPFLAGS (for the C/C++ preprocessor, mainly ‘-I’,‘-D’ and ‘-U’ flags),PKG_CFLAGS,PKG_CXXFLAGS,PKG_FFLAGS,PKG_OBJCFLAGS, andPKG_OBJCXXFLAGS(for the C, C++, Fortran, Objective C, and Objective C++compilers, respectively) in the fileMakevars in the compilationdirectory (or, of course, create the object files directly from thecommand line).Similarly, variablePKG_LIBS inMakevars can be used foradditional ‘-l’ and ‘-L’ flags to be passed to the linker whenbuilding the shared object. (Supplying linker commands as arguments toR CMD SHLIB will take precedence overPKG_LIBS inMakevars.)

It is possible to arrange to include compiled code from other languagesby setting the macro ‘OBJECTS’ in fileMakevars, togetherwith suitable rules to make the objects.

Flags that are already set (for example in fileetcR_ARCH/Makeconf) can be overridden by the environmentvariableMAKEFLAGS (at least for systems using a POSIX-compliantmake), as in (Bourne shell syntax)

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

It is also possible to set such variables in personalMakevarsfiles, which are read after the localMakevars and the systemmakefiles or in a site-wideMakevars.site file.SeeCustomizing package compilation inR Installation and Administrationfor more information.

Note that asR CMD SHLIB uses Make, it will not remake a sharedobject just because the flags have changed, and iftest.c andtest.f both exist in the current directory

R CMD SHLIB test.f

will compiletest.c!

If thesrc subdirectory of an add-on package contains source codewith one of the extensions listed above or a fileMakevars butnot a fileMakefile,R CMD INSTALL creates ashared object (for loading into R throughuseDynlib in theNAMESPACE, or in the.onLoad function of the package)using theR CMD SHLIB mechanism. If fileMakevarsexists it is read first, then the system makefile and then any personalMakevars files.

If thesrc subdirectory of package contains a fileMakefile, this is used byR CMD INSTALL in place of theR CMD SHLIB mechanism.make is called with makefilesR_HOME/etcR_ARCH/Makeconf,src/Makefile andany personalMakevars files (in that order). The first targetfound insrc/Makefile is used.

It is better to make use of aMakevars file rather than aMakefile: the latter should be needed only exceptionally.

Under Windows the same commands work, butMakevars.win will beused in preference toMakevars, and onlysrc/Makefile.winwill be used byR CMD INSTALL withsrc/Makefile beingignored. Since R 4.2.0,Makevars.ucrt will be used in preference toMakevars.win andsrc/Makefile.ucrt will be used in preferencetosrc/Makefile.win.For past experiences of building DLLs with a variety ofcompilers, see file ‘README.packages’.Under Windows you can supply an exports definitions file calleddllname-win.def: otherwise all entry points in objects (butnot libraries) supplied toR CMD SHLIB will be exported from theDLL. An example isstats-win.def for thestats package: aCRAN example in packagefastICA.

If you feel tempted to read the source code and subvert thesemechanisms, please resist. Far too much developer time has been wastedin chasing down errors caused by failures to follow this documentation,and even more by package authors demanding explanations as to why theirpackages no longer work.In particular, undocumented environment ormake variables arenot for use by package writers and are subject to change without notice.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.6 Interfacing C++ code

Suppose we have the following hypothetical C++ library, consisting ofthe two filesX.h andX.cpp, and implementing the twoclassesX andY which we want to use in R.

// X.hclass X {public: X (); ~X ();};class Y {public: Y (); ~Y ();};
// X.cpp#include <R.h>#include "X.h"static Y y;X::X()  { REprintf("constructor X\n"); }X::~X() { REprintf("destructor X\n");  }Y::Y()  { REprintf("constructor Y\n"); }Y::~Y() { REprintf("destructor Y\n");  }

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

extern "C" {}

For example,

// X_main.cpp:#include "X.h"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, theC++ initialization code (and hence the constructor of the staticvariableY) are not called. On a properly configured system, onecan simply use

R CMD SHLIB X.cpp X_main.cpp

to create the shared object, typicallyX.so (the file nameextension may be different on your platform). Now starting R yields

R version 2.14.1 Patched (2012-01-16 r58124)Copyright (C) 2012 The R Foundation for Statistical Computing...Type    "q()" to quit R.
R> dyn.load(paste("X", .Platform$dynlib.ext, sep = ""))constructor YR> .C("X_main")constructor Xdestructor Xlist()R> q()Save workspace image? [y/n/c]: ydestructor Y

The R for WindowsFAQ (rw-FAQ) contains details of howto compile this example under Windows.

Earlier versions of this example used C++ iostreams: this is bestavoided. There is no guarantee that the output will appear in the Rconsole, and indeed it will not on the R for Windows console. UseR code or the C entry points (seePrinting) for all I/O if at allpossible. Examples have been seen where merely loading a DLL thatcontained calls to C++ I/O upset R’s own C I/O (for example byresetting buffers on open files).

Most R header files can be included within C++ programs but theyshouldnot be included within anextern "C" block (asthey include system headers156).

5.6.1 External C++ code

Quite a lot of external C++ software is header-only (e.g. most of theBoost ‘libraries’ including all those supplied by packageBH,and most of Armadillo as supplied by packageRcppArmadillo)and so is compiled when an R package which uses it is installed.This causes few problems.

A small number of external libraries used in R packages have a C++interface to a library of compiled code, e.g. packagessfandrjags. This raises many more problems! The C++ interfaceuses name-mangling and theABI157may depend on the compiler, version and even C++ defines158,so requires the package C++ code to be compiled in exactly the same wayas the library (and what that was is often undocumented).

Even fewer external libraries use C++ internally but present a Cinterface, such as GEOS used bysf and other packages. Theserequire the C++ runtime library to be linked into the package’s sharedobject/DLL, and this is best done by including a dummy C++ file in thepackage sources.

There is a trend to link to the C++ interfaces offered by C softwaresuch ashdf5,pcre andImageMagick. Their Cinterfaces are much preferred for portability (and can be used from C++code). Also, the C++ interfaces are often optional in the softwarebuild or packaged separately and so users installing from packagesources are less likely to already have them installed.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.7 Fortran I/O

We have already warned against the use of C++ iostreams not leastbecause output is not guaranteed to appear on the R console, and thiswarning applies equally to Fortran output to units*and6. SeePrinting from Fortran, which describes workarounds.

When R was first developed, most Fortran compilers implemented I/O ontop of the C I/O system and so the two interworked successfully. Thiswas true ofg77, but no longer ofgfortran as usedingcc 4 and later. In particular, any package that makes useof Fortran I/O will when compiled on Windows interfere with C I/O: whenthe Fortran I/O support code is initialized (typically when the packageis loaded) the Cstdout andstderr are switched toLF line endings. (Functioninit in filesrc/modules/lapack/init_win.c shows how to mitigate this. In apackage this would look something like

#ifdef _WIN32# include <fcntl.h>#endifvoid R_init_mypkgname(DllInfo *dll){    // Native symbol registration calls#ifdef _WIN32    // gfortran I/O initialization sets these to _O_BINARY    setmode(1, _O_TEXT); /* stdout */    setmode(2, _O_TEXT); /* stderr */#endif}

in the file used for native symbol registration.)


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.8 Linking to other packages

It is not in general possible to link a DLL in packagepackA to aDLL provided by packagepackB (for the security reasons mentionedindyn.load anddyn.unload, and also because some platformsdistinguish between shared objects and dynamic libraries), but it is onWindows.

Note that there can be tricky versioning issues here, as packagepackB could be re-installed after packagepackA — it isdesirable that the API provided by packagepackB remainsbackwards-compatible.

Shipping a static library in packagepackB for other packages tolink to avoids most of the difficulties.


Next:, Up:Linking to other packages   [Contents][Index]

5.8.1 Unix-alikes

It is possible to link a shared object in packagepackA to alibrary provided by packagepackB under limited circumstanceson a Unix-alike OS. There are severe portability issues, so this is notrecommended for a distributed package.

This is easiest ifpackB provides a static librarypackB/lib/libpackB.a. (Note using directorylib ratherthanlibs is conventional, and architecture-specificsub-directories may be needed and are assumed in the sample codebelow. The code in the static library will need to be compiled withPIC flags on platforms where it matters.) Then as the code frompackagepackB is incorporated when packagepackA isinstalled, we only need to find the static library at install time forpackagepackA. The only issue is to find packagepackB, andfor that we can ask R by something like (long lines broken fordisplay here)

PKGB_PATH=`echo 'library(packB);  cat(system.file("lib",  package="packB", mustWork=TRUE))' \ | "${R_HOME}/bin/R" --vanilla --no-echo`PKG_LIBS="$(PKGB_PATH)$(R_ARCH)/libpackB.a"

For a dynamic librarypackB/lib/libpackB.so(packB/lib/libpackB.dylib on macOS: note that you cannot link toa shared object,.so, on that platform) we could use

PKGB_PATH=`echo 'library(packB);  cat(system.file("lib", package="packB", mustWork=TRUE))' \ | "${R_HOME}/bin/R" --vanilla --no-echo`PKG_LIBS=-L"$(PKGB_PATH)$(R_ARCH)" -lpackB

This will work for installation, but very likely not when packagepackB is loaded, as the path to packagepackB’slibdirectory is not in theld.so159 search path. You can arrange toput it therebefore R is launched by setting (on someplatforms)LD_RUN_PATH orLD_LIBRARY_PATH or adding to theld.so cache (seeman ldconfig). On platforms thatsupport it, the path to the directory containing the dynamic library canbe hardcoded at install time (which assumes that the location of packagepackB will not be changed nor the package updated to a changedAPI). On systems with thegcc orclang and theGNU linker (e.g. Linux) and some others this can be done bye.g.

PKGB_PATH=`echo 'library(packB);  cat(system.file("lib", package="packB", mustWork=TRUE)))' \ | "${R_HOME}/bin/R" --vanilla --no-echo`PKG_LIBS=-L"$(PKGB_PATH)$(R_ARCH)" -Wl,-rpath,"$(PKGB_PATH)$(R_ARCH)" -lpackB

Some other systems (e.g. Solaris with its native linker) use-Rdir rather than-rpath,dir (and this is accepted bythe compiler as well as the linker).

It may be possible to figure out what is required semi-automaticallyfrom the result ofR CMD libtool --config (look for‘hardcode’).

Making headers provided by packagepackB available to the code tobe compiled in packagepackA can be done by theLinkingTomechanism (seeRegistering native routines).


Previous:, Up:Linking to other packages   [Contents][Index]

5.8.2 Windows

Suppose packagepackA wants to make use of compiled code providedbypackB in DLLpackB/libs/exB.dll, possibly the package’sDLLpackB/libs/packB.dll. (This can be extended to linking tomore than one package in a similar way.) There are three issues to beaddressed:

  • Making headers provided by packagepackB available to the code tobe compiled in packagepackA.

    This is done by theLinkingTo mechanism (seeRegistering native routines).

  • preparingpackA.dll to link topackB/libs/exB.dll.

    This needs an entry inMakevars.win orMakevars.ucrt of the form

    PKG_LIBS= -L<something> -lexB

    and one possibility is that<something> is the path to theinstalledpkgB/libs directory. To find that we need to ask Rwhere it is by something like

    PKGB_PATH=`echo 'library(packB);  cat(system.file("libs", package="packB", mustWork=TRUE))' \ | rterm --vanilla --no-echo`PKG_LIBS= -L"$(PKGB_PATH)$(R_ARCH)" -lexB

    Another possibility is to use an import library, shipping with packagepackA an exports fileexB.def. ThenMakevars.win (orMakevars.ucrt)could contain

    PKG_LIBS= -L. -lexBall: $(SHLIB) beforebefore: libexB.dll.alibexB.dll.a: exB.def

    and then installing packagepackA will make and use the importlibrary forexB.dll. (One way to prepare the exports file is tousepexports.exe.)

  • loadingpackA.dll which depends onexB.dll.

    IfexB.dll was used by packagepackB (because it is in factpackB.dll orpackB.dll depends on it) andpackB hasbeen loaded beforepackA, then nothing more needs to be done asexB.dll will already be loaded into the R executable. (Thisis the most common scenario.)

    More generally, we can use theDLLpath argument tolibrary.dynam to ensure thatexB.dll is found, for exampleby setting

    library.dynam("packA", pkg, lib,              DLLpath = system.file("libs", package="packB"))

    Note thatDLLpath can only set one path, and so for linking totwo or more packages you would need to resort to setting environmentvariablePATH.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.9 Handling R objects in C

Using C code to speed up the execution of an R function is often veryfruitful. Traditionally this has been donevia the.Cfunction in R. However, if a user wants to write C code usinginternal R data structures, then that can be done using the.Call and.External functions. The syntax for the callingfunction in R in each case is similar to that of.C, but thetwo functions have different C interfaces. Generally the.Callinterface is simpler to use, but.External is a little moregeneral.

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 nameof code that has already been loaded into R. Up to 65 R objectscan passed as arguments. The C side of the interface is

#include <R.h>#include <Rinternals.h>SEXP convolve2(SEXP a, SEXP b) ...

A call to.External is almost identical

.External("convolveE", a, b)

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

#include <R.h>#include <Rinternals.h>SEXP convolveE(SEXP args) ...

Hereargs is aLISTSXP, a Lisp-style pairlist from whichthe arguments can be extracted.

In each case the R objects are available for manipulationviaa set of functions and macros defined in the header fileRinternals.h or some S-compatibility macros160 SeeInterface functions.Call and.External for details on.Call and.External.

Before you decide to use.Call or.External, you shouldlook at other alternatives. First, consider working in interpreted Rcode; if this is fast enough, this is normally the best option. Youshould also see if using.C is enough. If the task to beperformed in C is simple enough involving only atomic vectors andrequiring no call to R,.C suffices. A great deal of usefulcode was written using just.C before.Call and.External were available. These interfaces allow much morecontrol, but they also impose much greater responsibilities so need tobe used with care. Neither.Call nor.External copy theirarguments: you should treat arguments you receive through theseinterfaces as read-only.

To handle R objects from within C code we use the macros and functionsthat have been used to implement the core parts of R. Apublic161 subset of these is defined in the header fileRinternals.h in the directoryR_INCLUDE_DIR (defaultR_HOME/include) that should be available on any Rinstallation.

A substantial amount of R, including the standard packages, isimplemented using the functions and macros described here, so the Rsource code provides a rich source of examples and “how to do it”: domake use of the source code for inspirational examples.

It is necessary to know something about how R objects are handled inC code. All the R objects you will deal with will be handled withthe typeSEXP162, which is apointer to a structure with typedefSEXPREC. Think of thisstructure as avariant type that can handle all the usual typesof R objects, that is vectors of various modes, functions,environments, language objects and so on. The details are given laterin this section and inR Internal Structures inR Internals,but for mostpurposes the programmer does not need to know them. Think rather of amodel such as that used by Visual Basic, in which R objects arehanded around in C code (as they are in interpreted R code) as thevariant type, and the appropriate part is extracted for, for example,numerical calculations, only when it is needed. As in interpreted Rcode, much use is made of coercion to force the variant object to theright type.


Next:, Up:Handling R objects in C   [Contents][Index]

5.9.1 Handling the effects of garbage collection

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 timegarbage collected. That is, someor all of the allocated memory not being used is freed or marked asre-usable.

The R object types are represented by a C structure defined by atypedefSEXPREC inRinternals.h. It contains severalthings among which are pointers to data blocks and to otherSEXPRECs. ASEXP is simply a pointer to aSEXPREC.

If you create an R object in your C code, you must tell R that youare using the object by using thePROTECT macro on a pointer tothe object. This tells R that the object is in use so it is notdestroyed during garbage collection. Notice that it is the object whichis protected, not the pointer variable. It is a common mistake tobelieve that if you invokedPROTECT(p) at some point thenp is protected from then on, but that is not true once a newobject is assigned top.

Protecting an R object automatically protects all the R objectspointed to in the correspondingSEXPREC, for example all elementsof a protected list are automatically protected.

The programmer is solely responsible for housekeeping the calls toPROTECT. There is a corresponding macroUNPROTECT thattakes as argument anint giving the number of objects tounprotect when they are no longer needed. The protection mechanism isstack-based, soUNPROTECT(n) unprotects the lastnobjects which were protected. The calls toPROTECT andUNPROTECT must balance when the user’s code returns and shouldbalance in all functions. R will warn about"stack imbalance in .Call" (or.External) if thehousekeeping is wrong.

Here is a small example of creating an R numeric vector in C code:

#include <R.h>#include <Rinternals.h>    SEXP ab;      ....    ab = PROTECT(RF_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 removedduring 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 ingeneral we do not know (nor want to know) what is hiding behind the Rmacros and functions we use, and any of them might cause memory to beallocated, hence garbage collection and hence our objectab to beremoved. It is usually wise to err on the side of caution and assumethat any of the R macros and functions might remove the object.

In some cases it is necessary to keep better track of whether protectionis really needed. Be particularly aware of situations where a largenumber of objects are generated. The pointer protection stack has afixed size (default 10,000) and can become full. It is not a good ideathen to justPROTECT everything in sight andUNPROTECTseveral thousand objects at the end. It will almost invariably bepossible to either assign the objects as part of another object (whichautomatically protects them) or unprotect them immediately after use.

There is a less-used macroUNPROTECT_PTR(s) that unprotects theobject pointed to by theSEXPs, even if it is not the top itemon the pointer protection stack. This macro was introduced for use in theparser, where the code interfacing with the R heap is generated and thegenerator cannot be configured to insert proper calls toPROTECT andUNPROTECT. However,UNPROTECT_PTR is dangerous to use incombination withUNPROTECT when the same object has been protectedmultiple times. It has been superseded by multi-set based functionsR_PreserveInMSet andR_ReleaseFromMSet, which protect objectsin a multi-set created byR_NewPreciousMSet and typically itselfprotected usingPROTECT. These functions should not be neededoutside parsers.

Sometimes an object is changed (for example duplicated, coerced orgrown) yet the current value needs to be protected. For these casesPROTECT_WITH_INDEX saves an index of the protection location thatcan be used to replace the protected value usingREPROTECT.For example (from the internal code foroptim)

    PROTECT_INDEX ipx;    ....    PROTECT_WITH_INDEX(s = Rf_eval(OS->R_fcall, OS->R_env), &ipx);    REPROTECT(s = Rf_coerceVector(s, REALSXP), ipx);

Note that it is dangerous to mixUNPROTECT_PTR also withPROTECT_WITH_INDEX, as the former changes the protectionlocations of objects that were protected after the one beingunprotected.

There is another way to avoid the effects of garbage collection: a calltoR_PreserveObject adds an object to an internal list of objectsnot to be collected, and a subsequent call toR_ReleaseObjectremoves it from that list. This provides a way for objects which arenot returned as part of R objects to be protected across calls tocompiled code: on the other hand it becomes the user’s responsibility torelease them when they are no longer needed (and this often requires theuse of a finalizer). It is less efficient than the normal protectionmechanism, and should be used sparingly.

For functions from packages as well as R to safely co-operate inprotecting objects, certain rules have to be followed:

  • Pointer-protection balance. Calls toPROTECT andUNPROTECTshould balance in each function. A function may only callUNPROTECT orREPROTECT on objects it has itself protected. Note that the pointerprotection stack balance is restored automatically on non-local transfer ofcontrol (SeeCondition handling and cleanup code.), as if a call toUNPROTECT was invoked with the right argument.
  • Caller protection. It is the responsibility of the caller that allarguments passed to a function are protected and will stay protected for thewhole execution of the callee. Typically this is achieved byPROTECTandUNPROTECT calls.
  • Protecting return values. Any R objects returned from a function areunprotected (the callee must maintain pointer-protection balance), and henceshould be protected immediately by the caller. To be safe against futurecode changes, assume that any R object returned from any function mayneed protection. Note that even when conceptually returning an existingprotected object, that object may be duplicated.
  • All functions/macros allocate. To be safe against future code changes,assume that any function or macro may allocate and hence garbage collectormay run and destroy unprotected objects.

It is always safe and recommended to follow those rules. In fact, severalR functions and macros protect their own arguments and some functions donot allocate or do not allocate when used in a certain way, but that issubject to change, so relying on that may be fragile.PROTECT andPROTECT_WITH_INDEX can be safely called with unprotected argumentsandUNPROTECT does not allocate.


Next:, Previous:, Up:Handling R objects in C   [Contents][Index]

5.9.2 Allocating storage

For many purposes it is sufficient to allocate R objects andmanipulate those. There are quite a fewRf_allocXxx functionsdefined inRinternals.h—you may want to explore them.

One that is commonly used isRf_allocVector, the C-level equivalentof R-levelvector() and its wrappers such asinteger()andcharacter(). One distinction is that whereas the Rfunctions always initialize the elements of the vector,Rf_allocVector only does so for lists, expressions and charactervectors (the cases where the elements are themselves R objects).Other useful allocation functions areRf_alloc3DArray,Rf_allocArray, andRf_allocMatrix.

At times it can be useful to allocate a larger initial result vector andresize it to a shorter length if that is sufficient. The functionsRf_lengthgets andRf_xlengthgets accomplish this; they areanalogous to usinglength(x) <- n in R. Typically thesefunctions return a freshly allocated object, but in some cases they mayre-use the supplied object.

When creating new result objects it can be useful to fill them in withvalues from an existing object. The functionsRf_copyVector andRf_copyMatrix can be used for this.Rf_copyMostAttributes canalso simplify setting up a result object; it is used internally forresults of arithmetic operations.

If storage is required for C objects during the calculations this isbest allocated by callingR_alloc; seeMemory allocation.All of these memory allocation routines do their own error-checking, sothe programmer may assume that they will raise an error and not returnif the memory cannot be allocated.


Next:, Previous:, Up:Handling R objects in C   [Contents][Index]

5.9.3 Details of R types

Users of theRinternals.h macros will need to know how the Rtypes are known internally. The different R data types arerepresented in C bySEXPTYPE. Some of these are familiar fromR and some are internal data types. The usual R object modes aregiven in the table.

SEXPTYPER equivalent
REALSXPnumeric with storage modedouble
INTSXPinteger
CPLXSXPcomplex
LGLSXPlogical
STRSXPcharacter
VECSXPlist (generic vector)
LISTSXPpairlist
DOTSXPa ‘’ object
NILSXPNULL
SYMSXPname/symbol
CLOSXPfunction or function closure
ENVSXPenvironment

Among the important internalSEXPTYPEs areLANGSXP,CHARSXP,PROMSXP, etc. (N.B.: although it ispossible to return objects of internal types, it is unsafe to do so asassumptions are made about how they are handled which may be violated atuser-level evaluation.) More details are given inR Internal Structures inR Internals.

Unless you are very sure about the type of the arguments, the codeshould check the data types. Sometimes it may also be necessary tocheck data types of objects created by evaluating an R expression inthe C code. You can use functions likeRf_isReal,Rf_isIntegerandRf_isString to do type checking.Other such functions declared in the header fileRinternals.hincludeRf_iisNull,Rf_iisSymbol,Rf_iisLogical,Rf_iisComplex,Rf_iisExpression, andRf_iisEnvironment.All of these take aSEXP as argument and return 1 or 0 toindicateTRUE orFALSE.

What happens if theSEXP is not of the correct type? Sometimesyou have no other option except to generate an error. You can use thefunctionRf_error for this. It is usually better to coerce theobject to the correct type. For example, if you find that anSEXP is of the typeINTEGER, but you need aREALobject, you can change the type by using

newSexp = PROTECT(Rf_coerceVector(oldSexp, REALSXP));

Protection is needed as a newobject is created; the objectformerly pointed to by theSEXP is still protected but nowunused.163

All the coercion functions do their own error-checking, and generateNAs with a warning or stop with an error as appropriate.

Note that these coercion functions arenot the same as callingas.numeric (and so on) in R code, as they do not dispatch onthe class of the object. Thus it is normally preferable to do thecoercion in the calling R code.

So far we have only seen how to create and coerce R objects from Ccode, and how to extract the numeric data from numeric R vectors.These can suffice to take us a long way in interfacing R objects tonumerical algorithms, but we may need to know a little more to createuseful return objects.


Next:, Previous:, Up:Handling R objects in C   [Contents][Index]

5.9.4 Attributes

Many R objects have attributes: some of the most useful are classesand thedim anddimnames that mark objects as matrices orarrays. It can also be helpful to work with thenames attributeof vectors.

To illustrate this, let us write code to take the outer product of twovectors (whichouter and%o% already do). As usual theR code is simple

out <- function(x, y){    storage.mode(x) <- storage.mode(y) <- "double"    .Call("out", x, y)}

where we expectx andy to be numeric vectors (possiblyinteger), possibly with names. This time we do the coercion in thecalling R code.

C code to do the computations is

#include <R.h>#include <Rinternals.h>SEXP out(SEXP x, SEXP y){    int nx = Rf_length(x), ny = Rf_length(y);    SEXP ans = PROTECT(Rf_allocMatrix(REALSXP, nx, ny));    double *rx = REAL(x), *ry = REAL(y), *rans = REAL(ans);    for(int i = 0; i < nx; i++) {        double tmp = rx[i];        for(int j = 0; j < ny; j++)            rans[i + nx*j] = tmp * ry[j];    }    UNPROTECT(1);    return ans;}

Note the wayREAL is used: as it is a function call it can beconsiderably faster to store the result and index that.

However, we would like to set thedimnames of the result. We can use

#include <R.h>#include <Rinternals.h>
SEXP out(SEXP x, SEXP y){    int nx = Rf_length(x), ny = Rf_length(y);    SEXP ans = PROTECT(Rf_allocMatrix(REALSXP, nx, ny));    double *rx = REAL(x), *ry = REAL(y), *rans = REAL(ans);    for(int i = 0; i < nx; i++) {      double tmp = rx[i];      for(int j = 0; j < ny; j++)        rans[i + nx*j] = tmp * ry[j];    }    SEXP dimnames = PROTECT(Rf_allocVector(VECSXP, 2));    SET_VECTOR_ELT(dimnames, 0, Rf_getAttrib(x, R_NamesSymbol));    SET_VECTOR_ELT(dimnames, 1, Rf_getAttrib(y, R_NamesSymbol));    Rf_setAttrib(ans, R_DimNamesSymbol, dimnames);
    UNPROTECT(2);    return ans;}

This example introduces several new features. TheRf_getAttrib andRf_setAttribfunctions get and set individual attributes. Their second argument is aSEXP defining the name in the symbol table of the attribute wewant; these and many such symbols are defined in the header fileRinternals.h.

There are shortcuts here too: the functionsRf_namesgets,Rf_dimgets andRf_dimnamesgets are the internal versions of thedefault methods ofnames<-,dim<- anddimnames<-(for vectors and arrays), and there are functions such asRf_GetColNames,Rf_GetRowNames,Rf_GetMatrixDimnames andRf_GetArrayDimnames.

What happens if we want to add an attribute that is not pre-defined? Weneed to add a symbol for itvia a call toRf_install. Suppose for illustration we wanted to add an attribute"version" with value3.0. We could use

SEXP version;version = PROTECT(Rf_allocVector(REALSXP, 1));REAL(version)[0] = 3.0;Rf_setAttrib(ans, Rf_install("version"), version);UNPROTECT(1);

UsingRf_install when it is not needed is harmless and provides asimple way to retrieve the symbol from the symbol table if it is alreadyinstalled. However, the lookup takes a non-trivial amount of time, soconsider code such as

static SEXP VerSymbol = NULL;...if (VerSymbol == NULL) VerSymbol = Rf_install("version");

if it is to be done frequently.

This example can be simplified by another convenience function:

SEXP version = PROTECT(Rf_ScalarReal(3.0));Rf_setAttrib(ans, Rf_install("version"), version);UNPROTECT(1);

If a result is to be a vector with all elements named, thenRf_mkNamed can be used to allocate a vector of a specified type.Names are provided as a C vector of strings terminated by an emptystring:

const char *nms[] = {"xi", "yi", "zi", ""};Rf_mkNamed(VECSXP, nms);

Symbols can also be installed or retrieved based on a name in aCHARSXP object using eitherRf_installChar orRf_installTrChar. These used to differ in handling characterencoding but have been identical since R 4.0.0.


Next:, Previous:, Up:Handling R objects in C   [Contents][Index]

5.9.5 Classes

In R the class is just the attribute named"class" so it canbe handled as such, but there is a shortcutRf_classgets. Supposewe want to give the return value in our example the class"mat".We can use

#include <R.h>#include <Rinternals.h>      ....    SEXP ans, dim, dimnames, class;      ....    class = PROTECT(Rf_allocVector(STRSXP, 1));    SET_STRING_ELT(class, 0, Rf_mkChar("mat"));    Rf_classgets(ans, class);    UNPROTECT(4);    return ans;}

As the value is a character vector, we have to know how to create thatfrom a C character array, which we do using the functionRf_mkChar.


Next:, Previous:, Up:Handling R objects in C   [Contents][Index]

5.9.6 S4 objects

Several functions are available for working with S4 objects and classesin C, including:

SEXP Rf_allocS4Object(void);SEXP Rf_asS4(SEXP, Rboolean, int);int R_check_class_etc(SEXP x, const char **valid);SEXP R_do_MAKE_CLASS(const char *what);SEXP R_do_new_object(SEXP class_def);SEXP R_do_slot(SEXP obj, SEXP name);SEXP R_do_slot_assign(SEXP obj, SEXP name, SEXP value);SEXP R_getClassDef  (const char *what);int R_has_slot(SEXP obj, SEXP name);

Next:, Previous:, Up:Handling R objects in C   [Contents][Index]

5.9.7 Handling lists

Some care is needed with lists, as R moved early on from usingLISP-like lists (now called “pairlists”) to S-like generic vectors.As a result, the appropriate test for an object of modelist isRf_isNewList, and we needRf_allocVector(VECSXP,n) andnotRf_allocList(n).

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

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

Then we can accessa$g asa[[2]] by

    double g;      ....    g = REAL(VECTOR_ELT(a, 1))[0];

This can rapidly become tedious, and the following function (based onone in packagestats) is very useful:

/* get the list element named str (ASCII), or return NULL */SEXP getListElement(SEXP list, const char *str){    SEXP elmt = R_NilValue, names = Rf_getAttrib(list, R_NamesSymbol);
    for (int i = 0; i < Rf_length(list); i++)        if(strcmp(CHAR(STRING_ELT(names, i)), str) == 0) {           /* ASCII only */           elmt = VECTOR_ELT(list, i);           break;        }    return elmt;}

and enables us to say

  double g;  g = REAL(getListElement(a, "g"))[0];

This code only works for names that are ASCII (seeCharacter encoding issues).


Next:, Previous:, Up:Handling R objects in C   [Contents][Index]

5.9.8 Handling character data

R character vectors are stored asSTRSXPs, a vector type likeVECSXP where every element is of typeCHARSXP. TheCHARSXP elements ofSTRSXPs are accessed usingSTRING_ELT andSET_STRING_ELT.

CHARSXPs are read-only objects and must never be modified. Inparticular, the C-style string contained in aCHARSXP should betreated as read-only and for this reason theCHAR function usedto access the character data of aCHARSXP returns(constchar *) (this also allows compilers to issue warnings about improperuse). SinceCHARSXPs are immutable, the sameCHARSXP canbe shared by anySTRSXP needing an element representing the samestring. R maintains a global cache ofCHARSXPs so that thereis only ever oneCHARSXP representing a given string in memory.It most cases it is easier to useRf_translateCharorRf_translateCharUTF8 to obtain the C string and it is saferagainst potential future changes in R (seeCharacter encoding issues).

You can obtain aCHARSXP by callingRf_mkChar and providing aNUL-terminated C-style string. This function will return a pre-existingCHARSXP if one with a matching string already exists, otherwiseit will create a new one and add it to the cache before returning it toyou. The variantRf_mkCharLen can be used to create aCHARSXP from part of a buffer and will ensure null-termination.

Note that R character strings are restricted to2^31 - 1bytes, and hence so should the input toRf_mkChar be (C allowslonger strings on 64-bit platforms).


Next:, Previous:, Up:Handling R objects in C   [Contents][Index]

5.9.9 Working with closures

New function closure objects can be created withR_mkClosure:

SEXP R_mkClosure(SEXP formals, SEXP body, SEXP rho);

The components of a closure can be extracted withR_ClosureFormals,R_ClosureBody, andR_ClosureEnv.For a byte compiled closureR_ClosureBody returns the compiledbody.R_ClosureExpr returns the body expression for bothcompiled and uncompiled closures. The expression for a compiled objectcan be obtained withR_BytecodeExpr.


Next:, Previous:, Up:Handling R objects in C   [Contents][Index]

5.9.10 Finding and setting variables

It will be usual that all the R objects needed in our C computationsare passed as arguments to.Call or.External, but it ispossible to find the values of R objects from within the C giventheir names. The following code is the equivalent ofget(name,envir = rho).

SEXP getvar(SEXP name, SEXP rho){    SEXP ans;    if (!Rf_isString(name) || Rf_length(name) != 1)        Rf_error("name is not a single string");    if (!Rf_isEnvironment(rho))        Rf_error("rho should be an environment");    ans = R_getVar(Rf_installChar(STRING_ELT(name, 0)), rho, TRUE);    if (TYPEOF(ans) != REALSXP || Rf_length(ans) == 0)        Rf_error("value is not a numeric vector with at least one element");    Rprintf("first value is %f\n", REAL(ans)[0]);    return R_NilValue;}

The main work is done byR_getVar, but to use it we need to installname as a namein the symbol table. As we wanted the value for internal use, we returnNULL.

R_getVar is similar to the R functionget. It signalsan error if there is no binding for the variable in theenvironment.R_getVarEx can be used to return a default value ifno binding is found; this corresponds to the R functionget0.The third argument toR_getVar andR_getVarEx correspondsto theinherits argument to the R functionget.

Functions with syntax

void Rf_defineVar(SEXP symbol, SEXP value, SEXP rho)void Rf_setVar(SEXP symbol, SEXP value, SEXP rho)

can be used to assign values to R variables.Rf_defineVarcreates a new binding or changes the value of an existing binding in thespecified environment frame; it is the analogue ofassign(symbol,value, envir = rho, inherits = FALSE), but unlikeassign,Rf_defineVar does not make a copy of the objectvalue.164Rf_setVar searches for an existingbinding forsymbol inrho or its enclosing environments.If a binding is found, its value is changed tovalue. Otherwise,a new binding with the specified value is created in the globalenvironment. This corresponds toassign(symbol, value, envir =rho, inherits = TRUE).

At times it may also be useful to create a new environment frame in C code.R_NewEnv is a C version of the R functionnew.env:

SEXP R_NewEnv(SEXP enclos, int hash, int size)

Next:, Previous:, Up:Handling R objects in C   [Contents][Index]

5.9.11 Some convenience functions

Some operations are done so frequently that there are conveniencefunctions to handle them. (All these are providedvia the headerfileRinternals.h.)

Suppose we wanted to pass a single logical argumentignore_quotes: we could use

    int ign = Rf_asLogical(ignore_quotes);    if(ign == NA_LOGICAL) Rf_error("'ignore_quotes' must be TRUE or FALSE");

which will do any coercion needed (at least from a vector argument), andreturnNA_LOGICAL if the value passed wasNA or coercionfailed. There are alsoRf_asInteger,Rf_asReal andRf_asComplex. The functionRf_asChar returns aCHARSXP.All of these functions ignore any elements of an input vector after thefirst.

Rf_asRboolean is a stricter version ofRf_asLogicalintroduced in R 4.5.0. It returns typeRboolean andgives an error for an input of length other than one, and forcoercion failure.Rf_asBool is a variant returning theC99/C23/C++ typebool.

The functionRf_asCharacterFactor converts a factor to a charactervector.

To return a length-one real vector we can use

    double x;    ...    return Rf_ScalarReal(x);

and there are versions of this for all the atomic vector types (those fora length-one character vector beingRf_ScalarString with argument aCHARSXP andRf_mkString with argumentconst char *).

SEXP Rf_ScalarReal(double);SEXP Rf_ScalarInteger(int);SEXP Rf_ScalarLogical(int)SEXP Rf_ScalarRaw(Rbyte);SEXP Rf_ScalarComplex(Rcomplex);SEXP Rf_ScalarString(SEXP);SEXP Rf_mkString(const char *);

Some of theRf_isXXXX functions differ from their apparentR-level counterparts: for exampleRf_isVector is true for anyatomic vector type (Rf_isVectorAtomic) and for lists and expressions(Rf_isVectorList) (with no check on attributes).Rf_isMatrix isa test of a length-2"dim" attribute.

Rboolean Rf_isVector(SEXP);Rboolean Rf_isVectorAtomic(SEXP);Rboolean Rf_isVectorList(SEXP);Rboolean Rf_isMatrix(SEXP);Rboolean Rf_isPairList(SEXP);Rboolean Rf_isPrimitive(SEXP);Rboolean Rf_isTs(SEXP);Rboolean Rf_isNumeric(SEXP);Rboolean Rf_isArray(SEXP);Rboolean Rf_isFactor(SEXP);Rboolean Rf_isObject(SEXP);Rboolean Rf_isFunction(SEXP);Rboolean Rf_isLanguage(SEXP);Rboolean Rf_isNewList(SEXP);Rboolean Rf_isList(SEXP);Rboolean Rf_isOrdered(SEXP);Rboolean Rf_isUnordered(SEXP);Rboolean Rf_isS4(SEXP);Rboolean Rf_isNumber(SEXP);Rboolean Rf_isDataFrame (SEXP);

Some additional predicates:

Rboolean Rf_isBlankString(const char *);Rboolean Rf_StringBlank(SEXP);Rboolean Rf_StringFalse(const char *);Rboolean Rf_StringTrue(const char *);int IS_LONG_VEC(SEXP);int IS_SCALAR(SEXP, int);

There are a series of small macros/functions to help construct pairlistsand language objects (whose internal structures just differ bySEXPTYPE). FunctionCONS(u, v) is the basic buildingblock: it constructs a pairlist fromu followed byv(which is a pairlist orR_NilValue).LCONS is a variantthat constructs a language object. FunctionsRf_list1 toRf_list6 construct a pairlist from one to six items, andRf_lang1 toRf_lang6 do the same for a language object (afunction to call plus zero to five arguments).FunctionsRf_elt andRf_lastElt find thei-th element andthe last element of a pairlist, andRf_nthcdr returns a pointer tothen-th position in the pairlist (whoseCAR is then-th item).

FunctionsRf_str2type andRf_type2str map R length-onecharacter strings to and fromSEXPTYPE numbers, andRf_type2char maps numbers to C character strings.Rf_type2str_nowarn does not issue a warning if theSEXPTYPEis invalid.


5.9.11.1 Semi-internal convenience functions

There is quite a collection of functions that may be used in your C codeif you are willing to adapt to rare API changes.These typically contain the “workhorses” of their R counterparts.

FunctionsRf_any_duplicated andRf_any_duplicated3 are fastversions of R’sany(duplicated(.)).

FunctionR_compute_identical corresponds to R’sidentical function.FunctionR_BindingIsLocked corresponds to R’sbindingIsLocked function.FunctionR_ParentEnv corresponds to R’sparent.env.

The C functionsRf_inherits andRf_topenv correspond tothe R functions of the same base name. The C functionRf_GetOption1 corresponds to the R functiongetOptionwithout specifying a default.Rf_GetOptionWidth returns the value of thewidth option as anint.The C functionRf_nlevels returns the number of levels of a factor.Unlike its R counterpart it always returns zero for non-factors.

For vectors the C functionRf_duplicated returns a logical vectorindicating for each element whether it is duplicated or not. A secondargument specifies the direction of the search.

The C functionR_lsInternal3 returns a character vector of thenames of variables in an environment. The second and third argumentsspecify whether all names are desired and whether the result should besorted.

Some convenience functions for working with pairlist objects includeRf_copyListMatrix,Rf_listAppend,Rf_isVectorizable,Rf_VectorToPairList, andRf_PairToVectorList

Some convenience functions for working with name spaces and environmentsincludeR_existsVarInFrame,R_removeVarFromFrame,R_PackageEnvName,R_IsPackageEnv,R_FindNamespace,R_IsNamespaceEnv, andR_NamespaceEnvSpec.

The C functionsRf_match andRf_pmatch correspond to the Rfunctions of the same base name.The C-level workhorse for partial matching is provided byRf_psmatch.

The C functionsR_forceAndCall andRf_isUnsorted correspondto the R functionsforceAndCall andis.unsorted.


Previous:, Up:Handling R objects in C   [Contents][Index]

5.9.12 Named objects and copying

[TheNAMED mechanism has been replaced by reference counting.]

When assignments are done in R such as

x <- 1:10y <- x

the named object is not necessarily copied, so after those twoassignmentsy andx are bound to the sameSEXPREC(the structure aSEXP points to). This means that any code whichalters one of them has to make a copy before modifying the copy if theusual R semantics are to apply. Note that whereas.C and.Fortran do copy their arguments,.Call and.External do not. SoRf_duplicate is commonly called onarguments to.Call before modifying them. If only the top levelis modified it may suffice to callRf_shallow_duplicate.

At times it may be necessary to copy attributes from one object toanother. This can be done usingDUPLICATE_ATTRIB orSHALLOW_DUPLICATE_ATTRIBANY_ATTRIB checks whether there are any attributes andCLEAR_ATTRIB removes all attributes.

However, at least some of this copying is unneeded. In the firstassignment shown,x <- 1:10, R first creates an object withvalue1:10 and then assigns it tox but ifx ismodified no copy is necessary as the temporary object with value1:10 cannot be referred to again. R distinguishes betweennamed and unnamed objectsvia a field in aSEXPREC thatcan be accessedvia the macrosNAMED andSET_NAMED. Thiscan take values

0

The object is not bound to any symbol

1

The object has been bound to exactly one symbol

>= 2

The object has potentially been bound to two or more symbols, and oneshould act as if another variable is currently bound to this value.The maximal value isNAMEDMAX.

Note the past tenses: R does not do currently do full referencecounting and there may currently be fewer bindings.

It is safe to modify the value of anySEXP for whichNAMED(foo) is zero, and ifNAMED(foo) is two or more, thevalue should be duplicated (via a call toRf_duplicate)before any modification. Note that it is the responsibility of theauthor of the code making the modification to do the duplication, evenif it isx whose value is being modified aftery <- x.

The caseNAMED(foo) == 1 allows some optimization, but it can beignored (and duplication done wheneverNAMED(foo) > 0). (Thisoptimization is not currently usable in user code.) It is intendedfor use within replacement functions. Suppose we used

x <- 1:10foo(x) <- 3

which is computed as

x <- 1:10x <- "foo<-"(x, 3)

Then inside"foo<-" the object pointing to the current value ofx will haveNAMED(foo) as one, and it would be safe tomodify it as the only symbol bound to it isx and that will berebound immediately. (Provided the remaining code in"foo<-"make no reference tox, and no one is going to attempt a directcall such asy <- "foo<-"(x).)

This mechanism was replaced in R 4.0.0. Tosupport future changes, package code should useNO_REFERENCES,MAYBE_REFERENCED,NOT_SHARED,MAYBE_SHARED, andMARK_NOT_MUTABLE.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.10 Interface functions.Call and.External

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

These two interfaces have almost the same functionality..Call isbased on the interface of the same name in S version 4, and.External is based on R’s.Internal..Externalis more complex but allows a variable number of arguments.


Next:, Up:Interface functions.Call and.External   [Contents][Index]

5.10.1 Calling.Call

Let us convert our finite convolution example to use.Call. Thecalling function in R is

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

which could hardly be simpler, but as we shall see all the typecoercion is transferred to the C code, which is

#include <R.h>#include <Rinternals.h>SEXP convolve2(SEXP a, SEXP b){    int na, nb, nab;    double *xa, *xb, *xab;    SEXP ab;    a = PROTECT(Rf_coerceVector(a, REALSXP));    b = PROTECT(Rf_coerceVector(b, REALSXP));    na = Rf_length(a); nb = Rf_length(b); nab = na + nb - 1;    ab = PROTECT(Rf_allocVector(REALSXP, nab));    xa = REAL(a); xb = REAL(b); xab = REAL(ab);    for(int i = 0; i < nab; i++) xab[i] = 0.0;    for(int i = 0; i < na; i++)        for(int j = 0; j < nb; j++) xab[i + j] += xa[i] * xb[j];    UNPROTECT(3);    return ab;}

Next:, Previous:, Up:Interface functions.Call and.External   [Contents][Index]

5.10.2 Calling.External

We can use the same example to illustrate.External. The Rcode 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, thistime as a single SEXP. The only change to the C code is how we handlethe arguments.

#include <R.h>#include <Rinternals.h>SEXP convolveE(SEXP args){    int i, j, na, nb, nab;    double *xa, *xb, *xab;    SEXP a, b, ab;    a = PROTECT(Rf_coerceVector(CADR(args), REALSXP));    b = PROTECT(Rf_coerceVector(CADDR(args), REALSXP));    ...}

Once again we do not need to protect the arguments, as in the R sideof the interface they are objects that are already in use. The macros

  first = CADR(args);  second = CADDR(args);  third = CADDDR(args);  fourth = CAD4R(args);  fifth  = CAD5R(args);

provide convenient ways to access the first five arguments. Moregenerally we can use theCDR andCAR 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 tohandle calls with a variable number of arguments, aslength(args)will give the number of arguments supplied (of which the first isignored). We may need to know the names (‘tags’) given to the actualarguments, which we can by using theTAG macro and usingsomething like the following example, that prints the names and the firstvalue of its arguments if they are vector types.

SEXP showArgs(SEXP args){    void *vmax = vmaxget();    args = CDR(args); /* skip 'name' */    for(int i = 0; args != R_NilValue; i++, args = CDR(args)) {        const char *name =            Rf_isNull(TAG(args)) ? "" : Rf_translateChar(PRINTNAME(TAG(args)));        SEXP el = CAR(args);        if (length(el) == 0) {            Rprintf("[%d] '%s' R type, length 0\n", i+1, name);           continue;        }
        switch(TYPEOF(el)) {        case REALSXP:            Rprintf("[%d] '%s' %f\n", i+1, name, REAL(el)[0]);            break;
        case LGLSXP:        case INTSXP:            Rprintf("[%d] '%s' %d\n", i+1, name, INTEGER(el)[0]);            break;
        case CPLXSXP:        {            Rcomplex cpl = COMPLEX(el)[0];            Rprintf("[%d] '%s' %f + %fi\n", i+1, name, cpl.r, cpl.i);        }            break;
        case STRSXP:            Rprintf("[%d] '%s' %s\n", i+1, name,                   Rf_translateChar(STRING_ELT(el, 0)));           break;
        default:            Rprintf("[%d] '%s' R type\n", i+1, name);       }    }    vmaxset(vmax);    return R_NilValue;}

This can be called by the wrapper function

showArgs <- function(...) invisible(.External("showArgs", ...))

Note that this style of programming is convenient but not necessary, asan alternative style is

showArgs1 <- function(...) invisible(.Call("showArgs1", list(...)))

The (very similar) C code is in the scripts.

Additional functions for accessing pairlist components areCAAR,CDAR,CDDR, andCDDDR.These components can be modified withSETCAR,SETCDR,SETCADR,SETCADDR,SETCADDDR, andSETCAD4R.


Previous:, Up:Interface functions.Call and.External   [Contents][Index]

5.10.3 Missing and special values

One piece of error-checking the.C call does (unlessNAOKis true) is to check for missing (NA) andIEEE specialvalues (Inf,-Inf andNaN) and give an error if anyare found. With the.Call interface these will be passed to ourcode. In this example the special values are no problem, asIEC 60559 arithmetic will handle them correctly. In the currentimplementation this is also true ofNA as it is a type ofNaN, but it is unwise to rely on such details. Thus we willre-write the code to handleNAs using macros defined inR_ext/Arith.h included byR.h.

The code changes are the same in any of the versions ofconvolve2orconvolveE:

    ...  for(int i = 0; i < na; i++)    for(int 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 theISNA macro, and the similar macrosISNAN(which checks forNaN orNA) andR_FINITE (which isfalse forNA and all the special values), only apply to numericvalues of typedouble. Missingness of integers, logicals andcharacter strings can be tested by equality to the constantsNA_INTEGER,NA_LOGICAL andNA_STRING. These andNA_REAL can be used to set elements of R vectors toNA.

The constantsR_NaN,R_PosInf andR_NegInf can beused to setdoubles to the special values.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.11 Evaluating R expressions from C

The main function we will use is

SEXP Rf_eval(SEXP expr, SEXP rho);

the equivalent of the interpreted R codeeval(expr, envir =rho) (sorho must be an environment), although we can also makeuse ofRf_findVar,Rf_defineVar andRf_findFun (whichrestricts the search to functions).

To see how this might be applied, here is a simplified internal versionoflapply for expressions, used as

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

with C code

SEXP lapply(SEXP list, SEXP expr, SEXP rho){    int n = Rf_length(list);    SEXP ans;    if(!Rf_isNewList(list)) Rf_error("'list' must be a list");    if(!Rf_isEnvironment(rho)) Rf_error("'rho' should be an environment");    ans = PROTECT(Rf_allocVector(VECSXP, n));    for(int i = 0; i < n; i++) {        Rf_defineVar(Rf_install("x"), VECTOR_ELT(list, i), rho);        SET_VECTOR_ELT(ans, i, Rf_eval(expr, rho));    }    Rf_setAttrib(ans, R_NamesSymbol, Rf_getAttrib(list, R_NamesSymbol));    UNPROTECT(1);    return ans;}

It would be closer tolapply if we could pass in a functionrather than an expression. One way to do this isvia interpretedR code as in the next example, but it is possible (if somewhatobscure) to do this in C code. The following is based on the code insrc/main/optimize.c.

SEXP lapply2(SEXP list, SEXP fn, SEXP rho){    int n = length(list);    SEXP R_fcall, ans;    if(!Rf_isNewList(list)) Rf_error("'list' must be a list");    if(!Rf_isFunction(fn)) Rf_error("'fn' must be a function");    if(!Rf_isEnvironment(rho)) Rf_error("'rho' should be an environment");    R_fcall = PROTECT(Rf_lang2(fn, R_NilValue));    ans = PROTECT(Rf_allocVector(VECSXP, n));    for(int i = 0; i < n; i++) {        SETCADR(R_fcall, VECTOR_ELT(list, i));        SET_VECTOR_ELT(ans, i, Rf_eval(R_fcall, rho));    }    Rf_setAttrib(ans, R_NamesSymbol, Rf_getAttrib(list, R_NamesSymbol));    UNPROTECT(2);    return ans;}

used by

.Call("lapply2", a, sum, new.env())

FunctionRf_lang2 creates an executable pairlist of two elements, butthis will only be clear to those with a knowledge of a LISP-likelanguage.

As a more comprehensive example of constructing an R call in C codeand evaluating, consider the following fragment. Similar code appears inthe definition ofdo_docall insrc/main/coerce.c.

    SEXP s, t;    t = s = PROTECT(RF_allocLang(3));    SETCAR(t, Rf_install("print")); t = CDR(t);    SETCAR(t,  CAR(a)); t = CDR(t);    SETCAR(t, Rf_ScalarInteger(digits));    SET_TAG(t, Rf_install("digits"));    Rf_eval(s, env);    UNPROTECT(1);

The functionRf_allocLang is available as of R 4.4.1; for olderversions replaceRf_allocLang(3) with

LCONS(R_NilValue, Rf_allocList(2))

At this pointCAR(a) is the R object to be printed, thecurrent attribute. There are three steps: the call is constructed asa pairlist of length 3, the list is filled in, and the expressionrepresented by the pairlist is evaluated.

A pairlist is quite distinct from a generic vector list, the onlyuser-visible form of list in R. A pairlist is a linked list (withCDR(t) computing the next entry), with items (accessed byCAR(t)) and names or tags (set bySET_TAG). In this callthere are to be three items, a symbol (pointing to the function to becalled) and two argument values, the first unnamed and the second named.Setting the type toLANGSXP makes this a call which can be evaluated.

Customarily, the evaluation environment is passed from the callingR code (seerho above). In special cases it is possible thatthe C code may need to obtain the current evaluation environmentwhich can be done viaR_GetCurrentEnv() function.


Next:, Up:Evaluating R expressions from C   [Contents][Index]

5.11.1 Zero-finding

In this section we re-work the example of Becker, Chambers &Wilks (1988, pp.~205–10) on finding a zero of a univariatefunction. The R code and an example are

zero <- function(f, guesses, tol = 1e-7) {    f.check <- function(x) {        x <- f(x)        if(!is.numeric(x)) stop("Need a numeric result")        as.double(x)    }    .Call("zero", body(f.check), as.double(guesses), as.double(tol),          new.env())}cube1 <- function(x) (x^2 + 1) * (x - 1.5)zero(cube1, c(0, 5))

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

SEXP mkans(double x){    // no need for PROTECT() here, as REAL(.) does not allocate:    SEXP ans = Rf_allocVector(REALSXP, 1);    REAL(ans)[0] = x;    return ans;}
double feval(double x, SEXP f, SEXP rho){    // a version with (too) much PROTECT()ion .. "better safe than sorry"    SEXP symbol, value;    PROTECT(symbol = Rf_install("x"));    PROTECT(value = mkans(x));    Rf_defineVar(symbol, value, rho);    UNPROTECT(2);    return(REAL(Rf_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) Rf_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;        }    }}

Previous:, Up:Evaluating R expressions from C   [Contents][Index]

5.11.2 Calculating numerical derivatives

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

An interpreted R version and an example are

numeric.deriv <- function(expr, theta, rho=sys.frame(sys.parent())){    eps <- sqrt(.Machine$double.eps)    ans <- eval(substitute(expr), rho)    grad <- matrix(, length(ans), length(theta),                   dimnames=list(NULL, theta))    for (i in seq_along(theta)) {        old <- get(theta[i], envir=rho)        delta <- eps * max(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 <- 2numeric.deriv(sin(omega*x*y), c("x", "y"))

whereexpr is an expression,theta a character vector ofvariable names andrho the environment to be used.

For the compiled version the call from R will be

.External("numeric_deriv",expr,theta,rho)

with example usage

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

Note the need to quote the expression to stop it being evaluated in thecaller.

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

#include <R.h>#include <Rinternals.h>#include <float.h> /* for DBL_EPSILON */SEXP numeric_deriv(SEXP args){    SEXP theta, expr, rho, ans, ans1, gradient, par, dimnames;    double tt, xx, delta, eps = sqrt(DBL_EPSILON), *rgr, *rans;    int i, start;
    expr = CADR(args);    if(!Rf_isString(theta = CADDR(args)))        Rf_error("theta should be of type character");    if(!Rf_isEnvironment(rho = CADDDR(args)))        Rf_error("rho should be an environment");
    ans = PROTECT(Rf_coerceVector(eval(expr, rho), REALSXP));    gradient = PROTECT(Rf_allocMatrix(REALSXP, LENGTH(ans), LENGTH(theta)));    rgr = REAL(gradient); rans = REAL(ans);
    for(i = 0, start = 0; i < LENGTH(theta); i++, start += LENGTH(ans)) {        par = PROTECT(Rf_findVar(Rf_installChar(STRING_ELT(theta, i)), rho));        tt = REAL(par)[0];        xx = fabs(tt);        delta = (xx < 1) ? eps : xx*eps;        REAL(par)[0] += delta;        ans1 = PROTECT(Rf_coerceVector(Rf_eval(expr, rho), REALSXP));        for(int j = 0; j < LENGTH(ans); j++)            rgr[j + start] = (REAL(ans1)[j] - rans[j])/delta;        REAL(par)[0] = tt;        UNPROTECT(2); /* par, ans1 */    }
    dimnames = PROTECT(Rf_allocVector(VECSXP, 2));    SET_VECTOR_ELT(dimnames, 1,  theta);    Rf_dimnamesgets(gradient, dimnames);    Rf_setAttrib(ans, Rf_install("gradient"), gradient);    UNPROTECT(3); /* ans  gradient  dimnames */    return ans;}

The code to handle the arguments is

    expr = CADR(args);    if(!Rf_isString(theta = CADDR(args)))        Rf_error("theta should be of type character");    if(!Rf_isEnvironment(rho = CADDDR(args)))        Rf_error("rho should be an environment");

Note that we check for correct types oftheta andrho butdo not check the type ofexpr. That is becauseeval canhandle many types of R objects other thanEXPRSXP. There isno useful coercion we can do, so we stop with an error message if thearguments are not of the correct mode.

The first step in the code is to evaluate the expression in theenvironmentrho, by

    ans = PROTECT(Rf_coerceVector(eval(expr, rho), REALSXP));

We then allocate space for the calculated derivative by

    gradient = PROTECT(Rf_allocMatrix(REALSXP, LENGTH(ans), LENGTH(theta)));

The first argument toRf_allocMatrix gives theSEXPTYPE ofthe matrix: here we want it to beREALSXP. The other twoarguments are the numbers of rows and columns. (Note thatLENGTHis intended to be used for vectors:Rf_length is more generallyapplicable.)

    for(i = 0, start = 0; i < LENGTH(theta); i++, start += LENGTH(ans)) {        par = PROTECT(Rf_findVar(Rf_installChar(STRING_ELT(theta, i)), rho));

Here, we are entering a for loop. We loop through each of thevariables. In thefor loop, we first create a symbolcorresponding to thei-th element of theSTRSXPtheta. Here,STRING_ELT(theta, i) accesses thei-th element of theSTRSXPtheta.installChar() installs the element as a name andRf_findVarfinds its value.

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

We first extract the real value of the parameter, then calculatedelta, the increment to be used for approximating the numericalderivative. Then we change the value stored inpar (inenvironmentrho) bydelta and evaluateexpr inenvironmentrho again. Because we are directly dealing withoriginal R memory locations here, R does the evaluation for thechanged parameter value.

        for(int j = 0; j < LENGTH(ans); j++)            rgr[j + start] = (REAL(ans1)[j] - rans[j])/delta;        REAL(par)[0] = tt;        UNPROTECT(2);    }

Now, we compute thei-th column of the gradient matrix. Note howit is accessed: R stores matrices by column (like Fortran).

    dimnames = PROTECT(Rf_allocVector(VECSXP, 2));    SET_VECTOR_ELT(dimnames, 1, theta);    Rf_dimnamesgets(gradient, dimnames);    Rf_setAttrib(ans, install("gradient"), gradient);    UNPROTECT(3);    return ans;}

First we add column names to the gradient matrix. This is done byallocating a list (aVECSXP) whose first element, the row names,isNULL (the default) and the second element, the column names,is set astheta. This list is then assigned as the attributehaving the symbolR_DimNamesSymbol. Finally we set the gradientmatrix as the gradient attribute ofans, unprotect the remainingprotected locations and return the answerans.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.12 Parsing R code from C

Suppose an R extension wants to accept an R expression from theuser and evaluate it. The previous section covered evaluation, but theexpression will be entered as text and needs to be parsed first. Asmall part of R’s parse interface is declared in header fileR_ext/Parse.h165.

An example of the usage can be found in the (example) Windows packagewindlgs included in the R source tree. The essential part is

#include <R.h>#include <Rinternals.h>#include <R_ext/Parse.h>SEXP menu_ttest3(){    char cmd[256];    SEXP cmdSexp, cmdexpr, ans = R_NilValue;    ParseStatus status;   ...    if(done == 1) {        cmdSexp = PROTECT(Rf_allocVector(STRSXP, 1));        SET_STRING_ELT(cmdSexp, 0, Rf_mkChar(cmd));        cmdexpr = PROTECT(R_ParseVector(cmdSexp, -1, &status, R_NilValue));        if (status != PARSE_OK) {            UNPROTECT(2);            Rf_error("invalid call %s", cmd);        }        /* Loop is needed here as EXPSEXP will be of length > 1 */        for(int i = 0; i < Rf_length(cmdexpr); i++)            ans = Rf_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 Rexpression.

R_ParseVector is essentially the code used to implementparse(text=) at R level. The first argument is a charactervector (corresponding totext) and the second the maximalnumber of expressions to parse (corresponding ton). The thirdargument is a pointer to a variable of an enumeration type, and it isnormal (asparse does) to regard all values other thanPARSE_OK as an error. Other values which might be returned arePARSE_INCOMPLETE (an incomplete expression was found) andPARSE_ERROR (a syntax error), in both cases the value returnedbeingR_NilValue. The fourth argument is a length one charactervector to be used as a filename in error messages, asrcfileobject or the RNULL object (as in the example above). If asrcfile object was used, asrcref attribute would beattached to the result, containing a list ofsrcref objects ofthe same length as the expression, to allow it to be echoed with itsoriginal formatting.

Two higher-level alternatives areR_ParseString andR_ParseEvalString:

Function:SEXPR_ParseString(const char *str)
Function:SEXPR_ParseEvalString(const char *str, SEXPenv)

R_ParseString Parses the code instr and returns theresulting expression. An error is signaled if parsingstr producesmore than one R expression.R_ParseEvalString first parsesstr, then evaluates the expression in the environmentenv,and returns the result.

An example fromsrc/main/objects.c:

call = R_ParseString("base::nameOfClass(X)");

Up:Parsing R code from C   [Contents][Index]

5.12.1 Accessing source references

The source references added by the parser are recorded by R’s evaluatoras it evaluates code. Two functionsmake these available to debuggers running C code:

SEXP R_GetCurrentSrcref(int skip);

This function checks the current evaluation stackfor entries that contain source reference information. Thereare two modes of operation.Ifskip == NA_INTEGER, theR_Srcref entry is checkedfollowed by entries in the call stack, until asrcref is found. Otherwise, theskip argument tells how manycalls to skip (counting from the top of the stack) beforereturning theSEXP of the call’ssrcref object orNULL if that call did not have one. Ifskip < 0,abs(skip) locations are counted up from the bottom of thestack. If too few or no source references are found,NULLis returned.

SEXP R_GetSrcFilename(SEXP srcref);

This function extracts the filename from the source reference fordisplay, returning a length 1 character vector containing thefilename. If no name is found,"" is returned.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.13 External pointers and weak references

TheSEXPTYPEsEXTPTRSXP andWEAKREFSXP can beencountered at R level, but are created in C code.

External pointerSEXPs are intended to handle references to Cstructures such as ‘handles’, and are used for this purpose in packageRODBC for example. They are unusual in their copying semantics inthat when an R object is copied, the external pointer object is notduplicated. (For this reason external pointers should only be used aspart of an object with normal semantics, for example an attribute or anelement of a list.)

An external pointer is created by

SEXP R_MakeExternalPtr(void *p, SEXP tag, SEXP prot);

wherep is the pointer (and hence this cannot portably be afunction pointer), andtag andprot are references toordinary R objects which will remain in existence (be protected fromgarbage collection) for the lifetime of the external pointer object. Auseful convention is to use thetag field for some form of typeidentification and theprot field for protecting the memory thatthe external pointer represents, if that memory is allocated from theR heap. Bothtag andprot can beR_NilValue,and often are.

An alternative way to create an external pointer from a function pointeris

typedef void * (*R_DL_FUNC)();SEXP R_MakeExternalPtrFn(R_DL_FUNC p, SEXP tag, SEXP prot);

The elements of an external pointer can be accessed and setvia

void *R_ExternalPtrAddr(SEXP s);DL_FUNC R_ExternalPtrAddrFn(SEXP s);SEXP R_ExternalPtrTag(SEXP s);SEXP R_ExternalPtrProtected(SEXP s);void R_ClearExternalPtr(SEXP s);void R_SetExternalPtrAddr(SEXP s, void *p);void R_SetExternalPtrTag(SEXP s, SEXP tag);void R_SetExternalPtrProtected(SEXP s, SEXP p);

Clearing a pointer sets its value to the CNULL pointer.

An external pointer object can have afinalizer, a piece of codeto be run when the object is garbage collected. This can be R codeor C code, and the various interfaces are, respectively.

void R_RegisterFinalizer(SEXP s, SEXP fun);void R_RegisterFinalizerEx(SEXP s, SEXP fun, Rboolean onexit);typedef void (*R_CFinalizer_t)(SEXP);void R_RegisterCFinalizer(SEXP s, R_CFinalizer_t fun);void R_RegisterCFinalizerEx(SEXP s, R_CFinalizer_t fun, Rboolean onexit);

The R function indicated byfun should be a function of asingle argument, the object to be finalized. R does not perform agarbage collection when shutting down, and theonexit argument ofthe extended forms can be used to ask that the finalizer be run during anormal shutdown of the R session. It is suggested that it is goodpractice to clear the pointer on finalization.

The only R level function for interacting with external pointers isreg.finalizer which can be used to set a finalizer.

It is probably not a good idea to allow an external pointer to besaved and then reloaded, but if this happens the pointer will beset to the CNULL pointer.

Finalizers can be run at many places in the code base and much of it,including the R interpreter, is not re-entrant. So great care isneeded in choosing the code to be run in a finalizer. Finalizers aremarked to be run at garbage collection but only run at a somewhat safepoint thereafter.

Weak references are used to allow the programmer to maintain informationon entities without preventing the garbage collection of the entitiesonce they become unreachable.

A weak reference contains a key and a value. The value is reachableif it is either reachable directly orvia weak references with reachablekeys. Once a value is determined to be unreachable during garbagecollection, the key and value are set toR_NilValue and thefinalizer will be run later in the garbage collection.

Weak reference objects are created by one of

SEXP R_MakeWeakRef(SEXP key, SEXP val, SEXP fin, Rboolean onexit);SEXP R_MakeWeakRefC(SEXP key, SEXP val, R_CFinalizer_t fin,                    Rboolean onexit);

where the R or C finalizer are specified in exactly the same way asfor an external pointer object (whose finalization interface isimplementedvia weak references).

The parts can be accessedvia

SEXP R_WeakRefKey(SEXP w);SEXP R_WeakRefValue(SEXP w);void R_RunWeakRefFinalizer(SEXP w);

A toy example of the use of weak references can be found athttps://homepage.stat.uiowa.edu/~luke/R/references/weakfinex.html,but that is used to add finalizers to external pointers which can now bedone more directly. At the time of writing noCRAN orBioconductor package used weak references.


Up:External pointers and weak references   [Contents][Index]

5.13.1 An example

PackageRODBC uses external pointers to maintain itschannels, connections to databases. There can be severalconnections open at once, and the status information for each is storedin a C structure (pointed to bythisHandle in the code extractbelow) that is returnedvia an external pointer as part of theRODBC‘channel’ (as the"handle_ptr" attribute). The external pointeris created by

    SEXP ans, ptr;    ans = PROTECT(Rf_allocVector(INTSXP, 1));    ptr = R_MakeExternalPtr(thisHandle, Rf_install("RODBC_channel"), R_NilValue);    PROTECT(ptr);    R_RegisterCFinalizerEx(ptr, chanFinalizer, TRUE);            ...    /* return the channel no */    INTEGER(ans)[0] = nChannels;    /* and the connection string as an attribute */    Rf_setAttrib(ans, Rf_install("connection.string"), constr);    Rf_setAttrib(ans, Rf_install("handle_ptr"), ptr);    UNPROTECT(3);    return ans;

Note the symbol given to identify the usage of the external pointer, andthe use of the finalizer. Since the final argument when registering thefinalizer isTRUE, the finalizer will be run at the end of theR session (unless it crashes). This is used to close and clean upthe connection to the database. The finalizer code is simply

static void chanFinalizer(SEXP ptr){    if(!R_ExternalPtrAddr(ptr)) return;    inRODBCClose(R_ExternalPtrAddr(ptr));    R_ClearExternalPtr(ptr); /* not really needed */}

Clearing the pointer and checking for aNULL pointer avoids anypossibility of attempting to close an already-closed channel.

R’s connections provide another example of using external pointers,in that case purely to be able to use a finalizer to close and destroy theconnection if it is no longer is use.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.14 Vector accessor functions

The vector accessors likeREAL,INTEGER,LOGICAL,RAW,COMPLEX, andVECTOR_ELT arefunctionswhen used in R extensions. (For efficiency they may be macros orinline functions when used in the R source code, apart fromSET_STRING_ELT andSET_VECTOR_ELT which are alwaysfunctions. When used outside the R source code all vector accessorsare functions.)There are also read-only versions that return aconst data pointer.For example, the return type ofREAL_RO isconst double *.These accessor functions check that they are being used on anappropriate type ofSEXP. ForVECSXP andSTRSXPobjects only read-only pointers are available as modifying their datadirectly would violate assumptions the memory manager depends on.DATAPTR_RO returns a generic read-only data pointer for anyvector object.

N.B. These will return a valid data pointer only for vectors ofpositive length. Zero-length vectors have no ‘data’ and these accessorswill usually return an invalid pointer, for example to address0x000000000001. So usages such as

memcpy(REAL(newx), REAL_RO(x), LENGTH(x) * sizeof(double));

are undefined behaviour without a prior check on the length ofx.

Formerly it was possible for packages to obtain internal versions ofsome accessors by defining ‘USE_RINTERNALS’ before includingRinternals.h. This is no longer the case. Defining‘USE_RINTERNALS’ now has no effect.

Atomic vector elements can also be accessed and set using element-wiseoperations likeINTEGER_ELT andSET_INTEGER_ELT. Forobjects with a compact representation using these may avoid fullymaterializing the object. In contrast, obtaining a data pointer willhave to fully materialize the object.


Next:, Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.15 Character encoding issues

CHARSXPs can be marked as coming from a known encoding (Latin-1or UTF-8). This is mainly intended for human-readable output, and mostpackages can just treat suchCHARSXPs as a whole. However, ifthey need to be interpreted as characters or output at C level then itwould normally be correct to ensure that they are converted to theencoding of the current locale: this can be done by accessing the datain theCHARSXP byRf_translateChar rather than byCHAR. If re-encoding is needed this allocates memory withR_alloc which thus persists to the end of the.Call/.External call unlessvmaxset is used(seeTransient storage allocation).

There is a similar functionRf_translateCharUTF8 which converts toUTF-8: this has the advantage that a faithful translation is almostalways possible (whereas only a few languages can be represented in theencoding of the current locale unless that is UTF-8).

BothRf_translateChar andRf_translateCharUTF8 will translateany input, using escapes such as ‘<A9>’ and ‘<U+0093>’ torepresent untranslatable parts of the input.

There is a public interface to the encoding marked onCHARSXPsvia

typedef enum {CE_NATIVE, CE_UTF8, CE_LATIN1, CE_BYTES, CE_SYMBOL, CE_ANY} cetype_t;cetype_t Rf_getCharCE(SEXP);SEXP Rf_mkCharCE(const char *, cetype_t);

OnlyCE_UTF8 andCE_LATIN1 are marked onCHARSXPs(and soRf_getCharCE will only return one of the first three),and these should only be used on non-ASCII strings. ValueCE_BYTES is used to makeCHARSXPs which should be regardedas a set of bytes and not translated. ValueCE_SYMBOL is usedinternally to indicate Adobe Symbol encoding. ValueCE_ANY isused to indicate a character string that will not need re-encoding –this is used for character strings known to be inASCII, andcan also be used as an input parameter where the intention is that thestring is treated as a series of bytes. (See the comments underRf_mkChar about the length of input allowed.)

Function

Rboolean Rf_charIsASCII(SEXP);

can be used to detect whether a givenCHARSXP represents an ASCIIstring. The implementation is equivalent to checking individual characters,but may be faster.

Function

Rboolean Rf_charIsUTF8(SEXP);

can be used to detect whether the internal representation of a givenCHARSXP accessed viaCHAR is UTF-8 (including ASCII). Thisfunction is rarely needed and specifically is not needed withRf_translateCharUTF8, because such check is already included. However,when needed, it is better to use it in preference ofRf_getCharCE, as itis safer against future changes in the semantics of encoding marks andcovers strings internally represented in the native encoding. NotethatRf_charIsUTF8() is not equivalent togetCharCE() == CE_UTF8.

Similarly, function

Rboolean Rf_charIsLatin1(SEXP);

can be used to detect whether the internal representation of a givenCHARSXP accessed viaCHAR is latin1 (including ASCII). It isnot equivalent toRf_getCharCE() == CE_LATIN1.

Function

const char *Rf_reEnc(const char *x, cetype_t ce_in, cetype_t ce_out,                     int subst);

can be used to re-encode character strings: likeRf_translateChar itreturns a string allocated byR_alloc. This can translate fromCE_SYMBOL toCE_UTF8, but not conversely. Argumentsubst controls what to do with untranslatable characters orinvalid input: this is done byte-by-byte with1 indicates tooutput hex of the form<a0>, and2 to replace by.,with any other value causing the byte to produce no output.

There is also

SEXP Rf_mkCharLenCE(const char *, int, cetype_t);

to create marked character strings of a given length.


Previous:, Up:System and foreign language interfaces   [Contents][Index]

5.16 Writing compact-representation-friendly code

A simple way to iterate in C over the elements of an atomic vector is toobtain a data pointer and index into that pointer with standard Cindexing. However, if the object has a compact representation, thenobtaining the data pointer will force the object to be fullymaterialized. An alternative is to use one of the following functions toquery whether a data pointer is available.

Function:const int *LOGICAL_OR_NULL(SEXPx)
Function:const int *INTEGER_OR_NULL(SEXPx)
Function:const double *REAL_OR_NULL(SEXPx)
Function:const Rcomplex *COMPLEX_OR_NULL(SEXPx)
Function:const Rbyte *RAW_OR_NULL(SEXPx)
Function:const void *DATAPTR_OR_NULL(SEXPx)

These functions will return a data pointer if one is available. Forvectors with a compact representation these functions will returnNULL.

If a data pointer is not available, then code can access elements one ata time with functions likeREAL_ELT. This is often sufficient,but in some cases can be inefficient. An alternative is to request datafor contiguous blocks of elements. For a good choice of block size thiscan be nearly as efficient as direct pointer access.

Function:R_xlen_tINTEGER_GET_REGION(SEXPsx, R_xlen_ti, R_xlen_tn, int *buf)
Function:R_xlen_tLOGICAL_GET_REGION(SEXPsx, R_xlen_ti, R_xlen_tn, int *buf)
Function:R_xlen_tREAL_GET_REGION(SEXPsx, R_xlen_ti, R_xlen_tn, double *buf)
Function:R_xlen_tCOMPLEX_GET_REGION(SEXPsx, R_xlen_ti, R_xlen_tn, Rcomplex *buf)
Function:R_xlen_tRAW_GET_REGION(SEXPsx, R_xlen_ti, R_xlen_tn, Rbyte *buf)

These functions copy a contiguous set of up ton elementsstarting with elementi into a bufferbuf. The returnvalue is the actual number of elements copied, which may be less thann.

Macros inR_ext/Itermacros.h may help in implementing aniteration strategy.

Some functions useful in implementing new alternate representationclasses, beyond those defined inR_ext/Altrep.h, includeALTREP,ALTREP_CLASS,R_altrep_data1,R_set_altrep_data1,R_altrep_data2, andR_set_altrep_data2.

For some objects it may be possible to very efficiently determinewhether the object is sorted or contains noNA values. Thesefunctions can be used to query this information:

Function:intLOGICAL_NO_NA(SEXPx)
Function:intINTEGER_NO_NA(SEXPx)
Function:intREAL_NO_NA(SEXPx)
Function:intSTRING_NO_NA(SEXPx)

ATRUE result means it is known that there are noNAvalues. AFALSE result means it is not known whether there areanyNA values.

Function:intINTEGER_IS_SORTED(SEXPx)
Function:intREAL_IS_SORTED(SEXPx)
Function:intSTRING_IS_SORTED(SEXPx)

These functions return one ofSORTED_DECR,SORTED_INCR, orUNKNOWN_SORTEDNESS.


Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

6 The RAPI: entry points for C code

There are a large number of entry points in the R executable/DLL thatcan be called from C code (and a few that can be called from Fortrancode). Only those documented here are stable enough that they will onlybe changed with considerable notice.

As explained elsewhere in this manual, these functions should only becalled from the main thread of the R process. (Doing otherwise canresult in memory corruption and very hard-to-debug segfaults.)

The recommended procedure to use these is to include the header fileR.h in your C code by

#include <R.h>

This will include several other header files from the directoryR_INCLUDE_DIR/R_ext, and there are other header filesthere that can be included too, but many of the features they containshould be regarded as undocumented and unstable.

Most of these header files, including all those included byR.h,can be used from C++ code. (However, they cannot safely be included inaextern "C" { } block as they may include C++ headers whenincluded from C++ code—and whether this succeeds is system-specific).

Note: Because R re-maps many of its external names to avoid clashes withsystem or user code, it isessential to include the appropriateheader files when using these entry points.

This remapping can cause problems166,and can be eliminated by definingR_NO_REMAP (before includingany R headers) and prepending ‘Rf_’ toall the functionnames used fromRinternals.h andR_ext/Error.h. Theseproblems can usually be avoided by including other headers (such assystem headers and those for external software used by the package)before any R headers. (Headers from other packages may include Rheaders directly orvia inclusion from further packages, and maydefineR_NO_REMAP with or without includingRinternals.h.)

As from R 4.5.0,R_NO_REMAP is always defined when the Rheaders are included from C++ code.

If you decide to defineR_NO_REMAP in your code, do usesomething like

#ifndef R_NO_REMAP# define R_NO_REMAP#endif

to avoid distracting compiler warnings.

Some of these entry points are declared in headerRmath.h, mostof which are remapped there. That remapping can be eliminated bydefiningR_NO_REMAP_RMATH (before including any R headers) andprepending ‘Rf_’ to the function names used from that header except

exp_rand norm_rand unif_rand signrank_free wilcox_free

We can classify the entry points as

API

Entry points which are documented in this manual and declared in aninstalled header file. These can be used in distributed packages andideally will only be changed after deprecation. SeeAPI index.

public

Entry points declared in an installed header file that are exported onall R platforms but are not documented and subject to change withoutnotice. Do not use these in distributed code. Their declarations willeventually be moved out of installed header files.

private

Entry points that are used when building R and exported on all Rplatforms but are not declared in the installed header files.Do not use these in distributed code.

hidden

Entry points that are where possible (Windows and some modern Unix-alikecompilers/loaders when using R as a shared library) not exported.

experimental

Entry points declared in an installed header file that are part of anexperimental API, such asR_ext/Altrep.h. These are subject tochange, so package authors wishing to use these should be prepared toadapt. SeeExperimental API index.

embedding

Entry points intended primarily for embedding and creating newfront-ends. It is not clear that this needs to be a separate categorybut it may be useful to keep it separate for now. SeeEmbedding API index.

If you would like to use an entry point or variable that is notidentified as part of the API in this document, or is currently hidden,you can make a request for it to be made available. Entry points orvariables not identified as in the API may be changed or removed with nonotice as part of efforts to improve aspects of R.

Work in progress: Currently Entry points in the API areidentified in the source for this document with@apifun,@eapifun, and@embfun entries. Similarly,@apivar,@eapivar, and@embvar identifyvariables, and@apihdr,@eapihdr, and@embhdridentify headers in the API.@forfun identifies entry points tobe called as Fortran subroutines. This could be used for programmaticextraction, but the specific format is work in progress and even the waythis document is produced is subject to change.


Next:, Up:The RAPI: entry points for C code   [Contents][Index]

6.1 Memory allocation

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

These functions are declared in headerR_ext/RS.h which isincluded byR.h.


Next:, Up:Memory allocation   [Contents][Index]

6.1.1 Transient storage allocation

Here R will reclaim the memory at the end of the call to.C,.Call or.External. Use

char *R_alloc(size_tn, intsize)

which allocatesn units ofsize bytes each. A typical usage(from packagestats) is

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

(size_t is defined instddef.h which the header definingR_alloc includes.)

There is a similar call,S_alloc (named for compatibility with olderversions of S) which zeroes the memory allocated,

char *S_alloc(longn, intsize)

and

char *S_realloc(char *p, longnew, longold, intsize)

which (fornew >old) changes the allocation sizefromold tonew units, and zeroes the additional units. NB:these calls are best avoided aslong is insufficient for largememory allocations on 64-bit Windows (where it is limited to 2^31-1bytes).

This memory is taken from the heap, and released at the end of the.C,.Call or.External call. Users can also manageit, by noting the current position with a call tovmaxget andsubsequently clearing memory allocated by a call tovmaxset. Anexample might be

void *vmax = vmaxget()// a loop involving the use of R_alloc at each iterationvmaxset(vmax)

This is only recommended for experts.

Note that this memory will be freed on error or user interrupt(if allowed: seeAllowing interrupts).

The memory returned is only guaranteed to be aligned as required fordouble pointers: take precautions if casting to a pointer whichneeds more. There is also

long double *R_allocLD(size_tn)

which is guaranteed to have the 16-byte alignment needed forlongdouble pointers on some platforms.

These functions should only be used in code called by.C etc,never from front-ends. They are not thread-safe.


Previous:, Up:Memory allocation   [Contents][Index]

6.1.2 User-controlled memory

The other form of memory allocation is an interface tomalloc,the interface providing R error signaling. This memory lasts untilfreed by the user and is additional to the memory allocated for the Rworkspace.

The interface macros are

type* R_Calloc(size_tn,type)type* R_Realloc(any *p, size_tn,type)void R_Free(any *p)

providing analogues ofcalloc,realloc andfree.If there is an error during allocation it is handled by R, so ifthese return the memory has been successfully allocated or freed.R_Free will set the pointerp toNULL.

Users should arrange toR_Free this memory when no longer needed,including on error or user interrupt. This can often be done mostconveniently from anon.exit action in the calling R function– seepwilcox for an example.

Do not assume that memory allocated byR_Calloc/R_Realloccomes from the same pool as used bymalloc:167 in particular do not usefree orstrdup with it.

Memory obtained by these macros should be aligned in the same way asmalloc, that is ‘suitably aligned for any kind of variable’.

Historically the macrosCalloc,Free andReallocwere used but have been removed in \R 4.5.0.

R_Calloc,R_Realloc, andR_Free are currentlyimplemented as macros expanding to calls toR_chk_calloc,R_chk_realloc, andR_chk_free, respectively. These shouldnot be called directly as they may be removed in the future.

char * CallocCharBuf(size_tn)void * Memcpy(q,p,n)void * Memzero(p,n)

CallocCharBuf(n) is shorthand forR_Calloc(n+1, char) to allowfor thenul terminator.Memcpy andMemzero taken items from arrayp and copy them to arrayq orzero them respectively.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.2 Error signaling

The basic error signaling routines are the equivalents ofstop andwarning in R code, and use the same interface.

void Rf_error(const char *format, ...);void Rf_warning(const char *format, ...);void Rf_errorcall(SEXPcall, const char *format, ...);void Rf_warningcall(SEXPcall, const char *format, ...);void Rf_warningcall_immediate(SEXPcall, const char *format, ...);

These have the same call sequences as calls toprintf, but in thesimplest case can be called with a single character string argumentgiving the error message. (Don’t do this if the string contains ‘%’or might otherwise be interpreted as a format.)

These are defined in headerR_ext/Error.h included byR.h.NB: whenR_NO_REMAP is defined (as is done forC++ code),Rf_error etc must be used.

HeaderR_ext/Error.h defines a macroNORET intended to beused only from C code (C++ code can use the[[noreturn]]attribute). This covers various ways to signal to the compiler that thefunction never returns. Because the usages of those ways differ by Cstandard, it should always be used at the beginning of a functiondeclaration, including beforestatic and attributes such asattribute_hidden.


Up:Error signaling   [Contents][Index]

6.2.1 Error signaling from Fortran

There are two interface function provided to callRf_error andRf_warning from Fortran code, in each case with a simple characterstring argument. They are defined as

subroutine rexit(message)subroutine rwarn(message)

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


Next:IEEE special values, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.3 Random number generation

The interface to R’s internal random number generation routines is

double unif_rand();double norm_rand();double exp_rand();double R_unif_index(double);

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

GetRNGstate();

and after all the required variates have been generated, call

PutRNGstate();

These essentially read in (or create).Random.seed and write itout after use.

These are defined in headerR_ext/Random.h. These functions arenever remapped.

The random number generator is private to R; there is no way toselect the kind of RNG nor set the seed except by evaluating calls tothe R functions which do so.

The C code behind R’srxxx functions can be accessed byincluding the header fileRmath.h; SeeDistribution functions.Those calls should also be preceded and followed by calls toGetRNGstate andPutRNGstate.


Up:Random number generation   [Contents][Index]

6.3.1 Random-number generation from Fortran

It was explained earlier that Fortran random-number generators shouldnot be used in R packages, not least as packages cannot safelyinitialize them. Rather a package should call R’s built-ingenerators: one way to do so is to use C wrappers like

#include <R_ext/RS.h>#include <R_ext/Random.h>void F77_SUB(getRNGseed)(void) {    GetRNGstate();}void F77_SUB(putRNGseed)(void) {    PutRNGstate();}double F77_SUB(unifRand)(void) {    return(unif_rand());}

called from Fortran code like

      ...      double precision X      call getRNGseed()      X = unifRand()      ...      call putRNGseed()

Alternatively one could use Fortran 2003’siso_c_binding moduleby something like (fixed-form Fortran 90 code):

      module rngfuncs        use iso_c_binding        interface          double precision     *      function unifRand() bind(C, name = "unif_rand")          end function unifRand          subroutine getRNGseed() bind(C, name = "GetRNGstate")          end subroutine getRNGseed          subroutine putRNGseed() bind(C, name = "PutRNGstate")          end subroutine putRNGseed        end interface      end module rngfuncs      subroutine testit      use rngfuncs      double precision X      call getRNGseed()      X = unifRand()      print *, X      call putRNGSeed()      end subroutine testit

Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.4 Missing andIEEE special values

A set of functions is provided to test forNA,Inf,-Inf andNaN. These functions are accessedvia macros:

ISNA(x)True for R’sNA onlyISNAN(x)True for R’sNA andIEEENaNR_FINITE(x)False forInf,-Inf,NA,NaN

andvia functionR_IsNaN which is true forNaN but notNA.

Do useR_FINITE rather thanisfinite orfinite; thelatter is often mendacious andisfinite is only available on asome platforms, on whichR_FINITE is a macro expanding toisfinite.

Currently in C codeISNAN is a macro callingisnan.(Since this gives problems on some C++ systems, if the R headers arecalled from C++ code a function call is used.)

You can check forInf or-Inf by testing equality toR_PosInf orR_NegInf, and set (but not test) anNAasNA_REAL.

All of the above apply todouble variables only. For integervariables there is a variable accessed by the macroNA_INTEGERwhich can used to set or test for missingness.

These are defined in headerR_ext/Arith.h included byR.h.


Next:, Previous:IEEE special values, Up:The RAPI: entry points for C code   [Contents][Index]

6.5 Printing

The most useful function for printing from a C routine compiled intoR isRprintf. This is used in exactly the same way asprintf, but is guaranteed to write to R’s output (which mightbe aGUI console rather than a file, and can be re-directed bysink). It is wise to write complete lines (including the"\n") before returning to R. It is defined inR_ext/Print.h.

The functionREprintf is similar but writes on the error stream(stderr) which may or may not be different from the standardoutput stream.

FunctionsRvprintf andREvprintf are analogues using thevprintf interface. Because that is a C99168 interface, they are only defined byR_ext/Print.h in C++code if the macroR_USE_C99_IN_CXX is defined before it isincluded or (as from R 4.0.0) a C++11 compiler is used.

Another circumstance when it may be important to use these functions iswhen using parallel computation on a cluster of computational nodes, astheir output will be re-directed/logged appropriately.


Up:Printing   [Contents][Index]

6.5.1 Printing from Fortran

On many systems Fortranwrite andprint statements can beused, but the output may not interleave well with that of C, and may beinvisible onGUI interfaces. They are not portable and bestavoided.

Some subroutines are provided to ease the output of information fromFortran code.

subroutine dblepr(label,nchar,data,ndata)subroutine realpr(label,nchar,data,ndata)subroutine intpr (label,nchar,data,ndata)

and from R 4.0.0,

subroutine labelpr(label,nchar)subroutine dblepr1(label,nchar,var)subroutine realpr1(label,nchar,var)subroutine intpr1 (label,nchar,var)

Herelabel is a character label of up to 255 characters,nchar is its length (which can be-1 if the whole label isto be used),data is an array of length at leastndata ofthe appropriate type (double precision,real andinteger respectively) andvar is a (scalar) variable.These routines print the label on one line and then printdata orvar as if it were an R vector on subsequent line(s). Note thatsome compilers will give an error or warning unlessdata is anarray: others will accept a scalar whenndata has value one orzero.NB: There is no check on the type ofdata orvar, so usingreal (including a real constant) instead ofdouble precision will give incorrect answers.

intpr works with zerondata so can be used to print alabel in earlier versions of R.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.6 Calling C from Fortran and vice versa

Naming conventions for symbols generated by Fortran differ by platform:it is not safe to assume that Fortran names appear to C with a trailingunderscore. To help cover up the platform-specific differences there isa set of macros169 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

On current platforms these are the same, but it is unwise torely on this. Note that names containing underscores were not legal inFortran 77, and are not portably handled by the above macros. (Also,all Fortran names for use by R are lower case, but this is notenforced by the macros.)

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

#include <R.h>void F77_SUB(rndstart)(void) { GetRNGstate(); }void F77_SUB(rndend)(void) { PutRNGstate(); }double F77_SUB(normrnd)(void) { return norm_rand(); }

to be called from Fortran as in

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

Note that this is not guaranteed to be portable, for the returnconventions might not be compatible between the C and Fortran compilersused. (Passing valuesvia arguments is safer.)

The standard packages, for examplestats, are a rich source offurther examples.

Where supported,link time optimization provides a reliable wayto check the consistency of calls to C from Fortran orviceversa.SeeUsing Link-time Optimization.One place where this occurs is the registration of.Fortran callsin C code (seeRegistering native routines). For example

init.c:10:13: warning: type of 'vsom_' does not match original declaration [-Wlto-type-mismatch]  extern void F77_NAME(vsom)(void *, void *, void *, void *,    void *, void *, void *, void *, void *);vsom.f90:20:33: note: type mismatch in parameter 9   subroutine vsom(neurons,dt,dtrows,dtcols,xdim,ydim,alpha,train)vsom.f90:20:33: note: 'vsom' was previously declared here

shows that a subroutine has been registered with 9 arguments (as that iswhat the.Fortran call used) but only has 8.


Next:, Up:Calling C from Fortran and vice versa   [Contents][Index]

6.6.1 Fortran character strings

Passing character strings from C to Fortran orvice versa isnot portable, but can be done with care. The internal representationsare different: a character array in C (or C++) isNUL-terminated so itslength can be computed bystrlen. Fortran character arrays aretypically stored as an array of bytes and a length. This matters whenpassing strings from C to Fortran orvice versa: in many casesone has been able to get away with passing the string but not thelength. However, in 2019 this changed forgfortran, startingwith version 9 but backported to versions 7 and 8. Several monthslater,gfortran 9.2 introduced an option

-ftail-call-workaround

and made it the current default but said it might be withdrawn in future.

Suppose we want a function to report a message from Fortran to R’sconsole (one could uselabelpr, orintpr with dummy data,but this might be the basis of a custom reporting function). Suppose theequivalent in Fortran would be

      subroutine rmsg(msg)      character*(*) msg      print *.msg      end

in filermsg.f. Usinggfortran 9.2 and later we canextract the C view by

gfortran -c -fc-prototypes-external rmsg.f

which gives

void rmsg_ (char *msg, size_t msg_len);

(wheresize_t applies to version 8 and later). We could re-writethat portably in C as

#ifndef USE_FC_LEN_T# define USE_FC_LEN_T#endif#include <Rconfig.h> // included by R.h, so define USE_FC_LEN_T earlyvoid F77_NAME(rmsg)(char *msg, FC_LEN_T msg_len){    char cmsg[msg_len+1];    strncpy(cmsg, msg, msg_len);    cmsg[msg_len] = '\0'; // nul-terminate the string, to be sure    // do something with 'cmsg'}

in code depending onR(>= 3.6.2). For earlier versions of R wecould just assume thatmsg isNUL-terminated (not guaranteed, butpeople have been getting away with it for many years), so the complete Cside might be

#ifndef USE_FC_LEN_T# define USE_FC_LEN_T#endif#include <Rconfig.h>#ifdef FC_LEN_Tvoid F77_NAME(rmsg)(char *msg, FC_LEN_T msg_len){    char cmsg[msg_len+1];    strncpy(cmsg, msg, msg_len);    cmsg[msg_len] = '\0';    // do something with 'cmsg'}#elsevoid F77_NAME(rmsg)(char *msg){    // do something with 'msg'}#endif

(USE_FC_LEN_T is the default as from R 4.3.0.)

An alternative is to use Fortran 2003 features to set up the Fortranroutine to pass a C-compatible character string. We could use somethinglike

      module cfuncs        use iso_c_binding, only: c_char, c_null_char        interface          subroutine cmsg(msg) bind(C, name = 'cmsg')            use iso_c_binding, only: c_char            character(kind = c_char):: msg(*)          end subroutine cmsg        end interface      end module      subroutine rmsg(msg)        use cfuncs        character(*) msg        call cmsg(msg//c_null_char) ! need to concatenate a nul terminator      end subroutine rmsg

where the C side is simply

void cmsg(const char *msg){    // do something with nul-terminated string 'msg'}

If you usebind to a C function as here, the only way to checkthat the bound definition is correct is to compile the package withLTO(which requires compatible C and Fortran compilers, usuallygcc andgfortran).

Passing a variable-length string from C to Fortran is trickier, buthttps://www.intel.com/content/www/us/en/docs/fortran-compiler/developer-guide-reference/2023-0/bind-c.htmlprovides a recipe. However, all the uses in BLAS and LAPACK are of asingle character, and for these we can write a wrapper in Fortranalong the lines of

      subroutine c_dgemm(transa, transb, m, n, k, alpha,     +     a, lda, b, ldb, beta, c, ldc)     +     bind(C, name = 'Cdgemm')        use iso_c_binding, only : c_char, c_int, c_double        character(c_char), intent(in) :: transa, transb        integer(c_int), intent(in) :: m, n, k, lda, ldb, ldc        real(c_double), intent(in) :: alpha, beta, a(lda, *), b(ldb, *)        real(c_double), intent(out) ::  c(ldc, *)        call dgemm(transa, transb, m, n, k, alpha,     +             a, lda, b, ldb, beta, c, ldc)      end subroutine c_dgemm

which is then called from C with declaration

voidCdgemm(const char *transa, const char *transb, const int *m,       const int *n, const int *k, const double *alpha,       const double *a, const int *lda, const double *b, const int *ldb,       const double *beta, double *c, const int *ldc);

Alternatively, do as R does and pass the character length(s) from Cto Fortran. A portable way to do this is

// before any R headers, or define in PKG_CPPFLAGS#ifndef  USE_FC_LEN_T# define USE_FC_LEN_T#endif#include <Rconfig.h>#include <R_ext/BLAS.h>#ifndef FCONE# define FCONE#endif...        F77_CALL(dgemm)("N", "T", &nrx, &ncy, &ncx, &one, x,                        &nrx, y, &nry, &zero, z, &nrx FCONE FCONE);

(Note there is no comma before or between theFCONE invocations.)Packages which call from C/C++ BLAS/LAPACK routines with characterarguments must adopt this approach: packages not using it will now failto install.


Next:, Previous:, Up:Calling C from Fortran and vice versa   [Contents][Index]

6.6.2 Fortran LOGICAL

Passing Fortran LOGICAL variables to/from C/C++ is potentiallycompiler-dependent. Fortran compilers have long used a 32-bit integertype so it is pretty portable to useint * on the C/C++ side.However, recent versions ofgfortranvia the option-fc-prototypes-external say the C equivalent isint_least32_t *: ‘Link-Time Optimization’ will reportint* as a mismatch. It is possible to useiso_c_binding in Fortran2003 to map LOGICAL variables to the C99 type_Bool, but it isusually simpler to pass integers.


Previous:, Up:Calling C from Fortran and vice versa   [Contents][Index]

6.6.3 Passing functions

A number of packages call C functions passed as arguments to Fortrancode along the lines of

c         subroutine fcn(m,n,x,fvec,iflag)c         integer m,n,iflagc         double precision x(n),fvec(m)...      subroutine lmdif(fcn, ...

where the C declaration and call are

void fcn_lmdif(int *m, int *n, double *par, double *fvec, int *iflag);void F77_NAME(lmdif)(void (*fcn_lmdif)(int *m, int *n, double *par,                                       double *fvec, int *iflag), ...F77_CALL(lmdif)(&fcn_lmdif, ...

This works on most platforms but depends on the C and Fortran compilersagreeing on calling conventions: this have been seen to fail. The mostportable solution seems to be to convert the Fortran code to C, perhapsusingf2c.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.7 Numerical analysis subroutines

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

The header filesR_ext/BLAS.h,R_ext/Lapack.h andR_ext/Linpack.h contain declarations of the BLAS, LAPACK andLINPACK linear algebra functions included in R. These are expressedas calls to Fortran subroutines, and they will also be usable fromusers’ Fortran code. Although not part of the officialAPI,this set of subroutines is unlikely to change (but might besupplemented).

The header fileRmath.h lists many other functions that areavailable and documented in the following subsections. Many of these areC interfaces to the code behind R functions, so the R functiondocumentation may give further details.

IfR_NO_REMAP_RMATH most of these will need to be prefixed byRf_: see the header file for which ones.


Next:, Up:Numerical analysis subroutines   [Contents][Index]

6.7.1 Distribution functions

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

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

double dnorm(doublex, doublemu, doublesigma, intgive_log);double pnorm(doublex, doublemu, doublesigma, intlower_tail,             intgive_log);double qnorm(doublep, doublemu, doublesigma, intlower_tail,             intlog_p);double rnorm(doublemu, doublesigma);

That is, the first argument gives the position for the density and CDFand probability for the quantile function, followed by thedistribution’s parameters. Argumentlower_tail should beTRUE (or1) for normal use, but can beFALSE (or0) if the probability of the upper tail is desired or specified.

Finally,give_log should be non-zero if the result is required onlog scale, andlog_p should be non-zero ifp has beenspecified 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 routinernorm returns one normalvariate. SeeRandom number generation, for the protocol in using therandom-variate routines.

Note that these argument sequences are (apart from the names and thatrnorm has non) mainly the same as the corresponding Rfunctions of the same name, so the documentation of the R functionscan be used. Note that the exponential and gamma distributions areparametrized byscale rather thanrate.

For reference, the following table gives the basic name (to be prefixedby ‘d’, ‘p’, ‘q’ or ‘r’ apart from the exceptionsnoted) and distribution-specific arguments for the complete set ofdistributions.

betabetaa,b
non-central betanbetaa,b,ncp
binomialbinomn,p
Cauchycauchylocation,scale
chi-squaredchisqdf
non-central chi-squarednchisqdf,ncp
exponentialexpscale (andnotrate)
Ffn1,n2
non-central Fnfn1,n2,ncp
gammagammashape,scale
geometricgeomp
hypergeometrichyperNR,NB,n
logisticlogislocation,scale
lognormallnormlogmean,logsd
negative binomialnbinomsize,prob
normalnormmu,sigma
Poissonpoislambda
Student’s ttn
non-central tntdf,delta
Studentized rangetukey (*)rr,cc,df
uniformunifa,b
Weibullweibullshape,scale
Wilcoxon rank sumwilcoxm,n
Wilcoxon signed ranksignrankn

Entries marked with an asterisk only have ‘p’ and ‘q’functions available, and none of the non-central distributions have‘r’ functions.

(If remapping is suppressed, the Normal distribution names areRf_dnorm4,Rf_pnorm5 andRf_qnorm5.)

Additionally, amultivariate RNG for the multinomial distribution is

void Rf_rmultinom(int n, double* prob, int K, int* rN)

whereK = length(prob),sum(prob[.]) == 1andrN must point to a length-K integer vectorn1 n2 .. nK where each entrynj=rN[j] is “filled” by a random binomial fromBin(n; prob[j]),constrained to sum(rN[.]) == n.

After calls todwilcox,pwilcox orqwilcox thefunctionwilcox_free() should be called, and similarlysignrank_free() for the signed rank functions.Sincewilcox_free() andsignrank_free() were only added toRmath.h in R  4.2.0, their use requires something like

#include "Rmath.h"#include "Rversion.h"#if R_VERSION < R_Version(4, 2, 0)extern void wilcox_free(void);extern void signrank_free(void);#endif

For the negative binomial distribution (‘nbinom’), in addition to the(size, prob) parametrization, the alternative(size, mu)parametrization is provided as well by functions ‘[dpqr]nbinom_mu()’,see?NegBinomial in R.

Functionsdpois_raw(x, *) anddbinom_raw(x, *) are versions of thePoisson and binomial probability mass functions which work continuously inx, whereasdbinom(x,*) anddpois(x,*) only return nonzero values for integerx.

double dbinom_raw(double x, double n, double p, double q, int give_log)double dpois_raw (double x, double lambda, int give_log)

Note thatdbinom_raw() returns both p and q = 1-p which may be advantageous when one of them is close to 1.


Next:, Previous:, Up:Numerical analysis subroutines   [Contents][Index]

6.7.2 Mathematical functions

Function:doublegammafn(doublex)
Function:doublelgammafn(doublex)
Function:doubledigamma(doublex)
Function:doubletrigamma(doublex)
Function:doubletetragamma(doublex)
Function:doublepentagamma(doublex)
Function:doublepsigamma(doublex, doublederiv)
Function:voiddpsifn(doublex, intn, intkode, intm, double*ans, int*nz, int*ierr)

The Gamma function, the natural logarithm of its absolute value andfirst four derivatives and the n-th derivative of Psi, the digammafunction, which is the derivative oflgammafn. In other words,digamma(x) is the same aspsigamma(x,0),trigamma(x) == psigamma(x,1), etc.The underlying workhorse,dpsifn(), is useful, e.g., when several derivatives oflog Gamma=lgammafn are desired. It computes andreturns inans[] the length-m sequence(-1)^(k+1) / gamma(k+1) * psi(k;x) fork = n ... n+m-1, where psi(k;x)is the k-th derivative of Psi(x), i.e.,psigamma(x,k). For more details, see the comments insrc/nmath/polygamma.c.

Function:doublebeta(doublea, doubleb)
Function:doublelbeta(doublea, doubleb)

The (complete) Beta function and its natural logarithm.

Function:doublechoose(doublen, doublek)
Function:doublelchoose(doublen, doublek)

The number of combinations ofk items chosen fromn andthe natural logarithm of its absolute value, generalized to arbitrary realn.k is rounded to the nearest integer (with a warning ifneeded).

Function:doublebessel_i(doublex, doublenu, doubleexpo)
Function:doublebessel_j(doublex, doublenu)
Function:doublebessel_k(doublex, doublenu, doubleexpo)
Function:doublebessel_y(doublex, doublenu)

Bessel functions of types I, J, K and Y with indexnu. Forbessel_i andbessel_k there is the option to returnexp(-x) I(xnu) or exp(x) K(xnu) ifexpo is 2. (Useexpo == 1 for unscaledvalues.)


Next:, Previous:, Up:Numerical analysis subroutines   [Contents][Index]

6.7.3 Numerical Utilities

There are a few other numerical utility functions available as entry points.

Function:doubleR_pow(doublex, doubley)
Function:doubleR_pow_di(doublex, inti)
Function:doublepow1p(doublex, doubley)

R_pow(x,y) andR_pow_di(x,i)computex^y andx^i, respectivelyusingR_FINITE checks and returning the proper result (the sameas R) for the cases wherex,y ori are 0 ormissing or infinite orNaN.

pow1p(x,y) computes(1 +x)^y, accuratelyeven for smallx, i.e., |x| << 1.

Function:doublelog1p(doublex)

Computeslog(1 +x) (log 1plus x), accuratelyeven for smallx, i.e., |x| << 1.

This should be provided by your platform, in which case it is notincluded inRmath.h, but is (probably) inmath.h whichRmath.h includes (except under C++, so it may not be declared forC++98).

Function:doublelog1pmx(doublex)

Computeslog(1 +x) -x (log 1plus xminusx),accurately even for smallx, i.e., |x| << 1.

Function:doublelog1pexp(doublex)

Computeslog(1 + exp(x)) (log 1plusexp),accurately, notably for largex, e.g., x > 720.

Function:doublelog1mexp(doublex)

Computeslog(1 - exp(-x)) (log 1minusexp),accurately, carefully for two regions ofx, optimally cuttingoff at log 2 (= 0.693147..), using((-x) > -M_LN2 ? log(-expm1(-x)) : log1p(-exp(-x))).

Function:doubleexpm1(doublex)

Computesexp(x) - 1 (exp xminus 1), accuratelyeven for smallx, i.e., |x| << 1.

This should be provided by your platform, in which case it is notincluded inRmath.h, but is (probably) inmath.h whichRmath.h includes (except under C++, so it may not be declared forC++98).

Function:doublelgamma1p(doublex)

Computeslog(gamma(x + 1)) (log(gamma(1plus x))),accurately even for smallx, i.e., 0 < x < 0.5.

Function:doublecospi(doublex)

Computescos(pi * x) (wherepi is 3.14159...),accurately, notably for half integerx.

This might be provided by your platform170, in which case it is not included inRmath.h, but isinmath.h whichRmath.h includes. (Ensure thatneithermath.h norcmath is included beforeRmath.h or define

#define __STDC_WANT_IEC_60559_FUNCS_EXT__ 1

before the first inclusion.)

Function:doublesinpi(doublex)

Computessin(pi * x) accurately, notably for (half) integerx.

This might be provided by your platform, in which case it is notincluded inRmath.h, but is inmath.h whichRmath.hincludes (but see the comments forcospi).

Function:doubleRtanpi(doublex)

Computestan(pi * x) accurately, notably for integerx, givingNaN for half integerx and exactly +1 or -1 for (non half)quarter integers.

Function:doubletanpi(doublex)

Computestan(pi * x) accurately for integerx with possiblyplatform dependent behavior for half (and quarter) integers.This might be provided by your platform, in which case it is not includedinRmath.h, but is inmath.h whichRmath.h includes(but see the comments forcospi).

Function:doublelogspace_add(doublelogx, doublelogy)
Function:doublelogspace_sub(doublelogx, doublelogy)
Function:doublelogspace_sum(const double*logx, intn)

Compute the log of a sum or difference from logs of terms, i.e., “x +y” aslog (exp(logx) + exp(logy)) and “x - y” aslog (exp(logx) - exp(logy)),and “sum_i x[i]” aslog (sum[i = 1:n exp(logx[i])] )without causing unnecessary overflows or throwing away too much accuracy.

Function:intimax2(intx, inty)
Function:intimin2(intx, inty)
Function:doublefmax2(doublex, doubley)
Function:doublefmin2(doublex, doubley)

Return the larger (max) or smaller (min) of two integer ordouble numbers, respectively. Note thatfmax2 andfmin2differ from C99/C++11’sfmax andfmin when one of thearguments is aNaN: these versions returnNaN.

Function:doublesign(doublex)

Compute thesignum function, where sign(x) is 1, 0, or-1, whenx is positive, 0, or negative, respectively, andNaN ifx is aNaN.

Function:doublefsign(doublex, doubley)

Performs “transfer of sign” and is defined as |x| * sign(y).

Function:doublefprec(doublex, doubledigits)

Returns the value ofx rounded todigitssignificantdecimal digits.

This is the function used by R’ssignif().

Function:doublefround(doublex, doubledigits)

Returns the value ofx rounded todigits decimal digits(after the decimal point).

This is the function used by R’sround(). (Note that C99/C++11provide around function but C++98 need not.)

Function:doubleftrunc(doublex)

Returns the value ofx truncated (to an integer value) towardszero.


Previous:, Up:Numerical analysis subroutines   [Contents][Index]

6.7.4 Mathematical constants

R has a set of commonly used mathematical constants encompassingconstants defined by POSIX and usually found in headersmath.handcmath, as well as further ones that are used in statisticalcomputations. These are defined to (at least) 30 digits accuracy inRmath.h. The following definitions useln(x) for thenatural logarithm (log(x) in R).

NameDefinition (ln = log)round(value, 7)
M_Ee2.7182818
M_LOG2Elog2(e)1.4426950
M_LOG10Elog10(e)0.4342945
M_LN2ln(2)0.6931472
M_LN10ln(10)2.3025851
M_PIpi3.1415927
M_PI_2pi/21.5707963
M_PI_4pi/40.7853982
M_1_PI1/pi0.3183099
M_2_PI2/pi0.6366198
M_2_SQRTPI2/sqrt(pi)1.1283792
M_SQRT2sqrt(2)1.4142136
M_SQRT1_21/sqrt(2)0.7071068
M_SQRT_3sqrt(3)1.7320508
M_SQRT_32sqrt(32)5.6568542
M_LOG10_2log10(2)0.3010300
M_2PI2*pi6.2831853
M_SQRT_PIsqrt(pi)1.7724539
M_1_SQRT_2PI1/sqrt(2*pi)0.3989423
M_SQRT_2dPIsqrt(2/pi)0.7978846
M_LN_SQRT_PIln(sqrt(pi))0.5723649
M_LN_SQRT_2PIln(sqrt(2*pi))0.9189385
M_LN_SQRT_PId2ln(sqrt(pi/2))0.2257914

For compatibility with S this file used to define the constantPI this is defunct and should be replaced byM_PI.HeaderConstants.h includes either C headerfloat.h orC++ headercfloat, which provide constants such asDBL_MAX.

The included headerR_ext/Boolean.h has enumeration constantsTRUE andFALSE of typeRboolean in order to providea way of using “logical” variables in C consistently. This canconflict with other software: for example it conflicts with the headersin IJG’sjpeg-9 (but not earlier versions).Rbooleancannot representNA171 andhence cannot be used for elements of R logical vectors.

TypeRboolean is being phased out: as from R 4.5.0 theheader also makes available the typebool and valuestrueandfalse. These are reserved words in C23 and C++11 andavailablevia headerstdbool.h as from C99. (Typebool is not a drop-in replacement forRboolean as it isusually stored in a byte andRboolean in anint, hence 4bytes.)

Some package maintainers may want to exclude the provision ofTRUE,FALSE,true,false andbool toavoid clashes with other headers such as the IJG ones mentioned above.This cannot be done entirely (the last three are keywords in C23 andC++11) but as from R 4.5.0 definingR_INCLUDE_BOOLEAN_Hto0 before including any header which includes this one (such asR.h andRinternals.h) skips its body.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.8 Optimization

The C code underlyingoptim can be accessed directly. The userneeds to supply a function to compute the function to be minimized, ofthe type

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

where the first argument is the number of parameters in the secondargument. The third argument is a pointer passed down from the callingroutine, 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 thegr argument. No functionis provided for finite-differencing, nor for approximating the Hessianat the result.

The interfaces (defined in headerR_ext/Applic.h) 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 isthe number of parameters,x orxin is the startingparameters on entry andx the final parameters on exit, withfinal value returned inFmin. Most of the other parameters canbe found from the help page foroptim: see the source codesrc/appl/lbfgsb.c for the values ofnbd, whichspecifies which bounds are to be used.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.9 Integration

The C code underlyingintegrate can be accessed directly. Theuser needs to supply avectorizing C function to compute thefunction to be integrated, of the type

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

wherex[] is both input and output and has lengthn, i.e.,a C function, sayfn, of typeintegr_fn must basically dofor(i in 1:n) x[i] := f(x[i], ex). The vectorization requirementcan be used to speed up the integrand instead of calling itntimes. Note that in the current implementation built on QUADPACK,n will be either 15 or 21. Theex argument is a pointerpassed down from the calling routine, normally used to carry auxiliaryinformation.

There are interfaces (defined in headerR_ext/Applic.h) forintegrals over finite and infinite intervals (or “ranges” or“integration boundaries”).

  • 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);
  • Infinite:
    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 thefinite range integral usingRdqags,a andb are theintegration interval bounds, whereas for an infinite range integral usingRdqagi,bound is the finite bound of the integration (ifthe integral is not doubly-infinite) andinf is a code indicatingthe kind of integration range,

inf = 1

corresponds to (bound, +Inf),

inf = -1

corresponds to (-Inf, bound),

inf = 2

corresponds to (-Inf, +Inf),

f andex define the integrand function, see above;epsabs andepsrel specify the absolute and relativeaccuracy requested,result,abserr andlast are theoutput componentsvalue,abs.err andsubdivisionsof the R function integrate, whereneval gives the number ofintegrand function evaluations, and the error codeier istranslated to R’sintegrate() $ message, look at that functiondefinition.limit corresponds tointegrate(...,subdivisions = *). It seems you should always define the two workarrays 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 insrc/appl/integrate.c givemore details, particularly about reasons for failure (ier >= 1).


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.10 Utility functions

R has a fairly comprehensive set of sort routines which are madeavailable to users’ C code.The following is declared in header fileRinternals.h.

Function:voidR_orderVector(int*indx, intn, SEXParglist, Rbooleannalast, Rbooleandecreasing)
Function:voidR_orderVector1(int*indx, intn, SEXPx, Rbooleannalast, Rbooleandecreasing)

R_orderVector() corresponds to R’sorder(..., na.last, decreasing).More specifically,indx <- order(x, y, na.last, decreasing) corresponds toR_orderVector(indx, n, Rf_lang2(x, y), nalast, decreasing) and forthree vectors,Rf_lang3(x,y,z) is used asarglist.

BothR_orderVector andR_orderVector1 assume the vectorindx to be allocated to length >= n. On return,indx[] contains a permutation of0:(n-1), i.e., 0-based Cindices (and not 1-based R indices, as R’sorder()).

When ordering only one vector,R_orderVector1 is faster andcorresponds (but is 0-based) to R’sindx <- order(x, na.last,decreasing). It was added in R 3.3.0.

All other sort routines are declared in header fileR_ext/Utils.h (included byR.h) and include the following.

Function:voidR_isort(int*x, intn)
Function:voidR_rsort(double*x, intn)
Function:voidR_csort(Rcomplex*x, intn)
Function:voidrsort_with_index(double*x, int*index, intn)

The first three sort integer, real (double) and complex datarespectively. (Complex numbers are sorted by the real part first thenthe imaginary part.)NAs are sorted last.

rsort_with_index sorts onx, and applies the samepermutation toindex.NAs are sorted last.

Function:voidRf_revsort(double*x, int*index, intn)

Is similar torsort_with_index but sorts into decreasing order,andNAs are not handled.

Function:voidRf_iPsort(int*x, intn, intk)
Function:voidRf_rPsort(double*x, intn, intk)
Function:voidRf_cPsort(Rcomplex*x, intn, intk)

These all provide (very) partial sorting: they permutex so thatx[k] is in the correct place with smaller values tothe left, larger ones to the right.

Function:voidR_qsort(double *v, size_ti, size_tj)
Function:voidR_qsort_I(double *v, int *I, inti, intj)
Function:voidR_qsort_int(int *iv, size_ti, size_tj)
Function:voidR_qsort_int_I(int *iv, int *I, inti, intj)

These routines sortv[i:j] oriv[i:j] (using 1-indexing, i.e.,v[1] is the first element) calling the quicksort algorithmas used by R’ssort(v, method = "quick") and documented on thehelp page for the R functionsort. The..._I()versions also return thesort.index() vector inI. Notethat the ordering isnot stable, so tied values may be permuted.

Note thatNAs are not handled (explicitly) and you shoulduse different sorting functions ifNAs can be present.

Function:subroutineqsort4(double precisionv, integerindx, integerii, integerjj)
Function:subroutineqsort3(double precisionv, integerii, integerjj)

The Fortran interface routines for sorting double precision vectors areqsort3 andqsort4, equivalent toR_qsort andR_qsort_I, respectively.

Function:voidR_max_col(double*matrix, int*nr, int*nc, int*maxes, int*ties_meth)

Given thenr bync matrixmatrix in column-major(“Fortran”)order,R_max_col() returns inmaxes[i-1] thecolumn number of the maximal element in thei-th row (the same asR’smax.col() function). In the case of ties (multiple maxima),*ties_meth is an integer code in1:3 determining the method:1 = “random”, 2 = “first” and 3 = “last”.See R’s help page?max.col.

Function:intfindInterval(double*xt, intn, doublex, Rbooleanrightmost_closed, Rbooleanall_inside, intilo, int*mflag)
Function:intfindInterval2(double*xt, intn, doublex, Rbooleanrightmost_closed, Rbooleanall_inside, Rbooleanleft_open, intilo, int*mflag)

Given the ordered vectorxt of lengthn, return the intervalor index ofx inxt[], typically max(i; 1 <= i <=n &xt[i] <=x) where we use 1-indexing as in R and Fortran (but not C). Ifrightmost_closed is true, also returnsn-1 ifxequalsxt[n]. Ifall_inside is not 0, theresult is coerced to lie in1:(n-1) even whenx isoutside thext[] range. On return,*mflag equals-1 ifx <xt[1],+1 ifx >=xt[n], and 0 otherwise.

The algorithm is particularly fast whenilo is set to the lastresult offindInterval() andx is a value of a sequence whichis increasing or decreasing for subsequent calls.

findInterval2() is a generalization offindInterval(),with an extraRboolean argumentleft_open. Settingleft_open = TRUE basically replaces all left-closed right-openintervals t) by left-open ones t], see the help pageof R functionfindInterval for details.

There is also anF77_CALL(interv)() version offindInterval() with the same arguments, but all pointers.

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

Function:char *R_tmpnam(const char *prefix, const char *tmpdir)
Function:char *R_tmpnam2(const char *prefix, const char *tmpdir, const char *fileext)
Function:voidR_free_tmpnam(char *name)

Return a pathname for a temporary file with name beginning withprefix and ending withfileext in directorytmpdir.ANULL prefix or extension is replaced by"". Note thatthe return value is dynamically allocated and should be freed usingR_free_tmpnam when no longer needed (unlike thesystem calltmpnam). Freeing the result usingfree is nolonger recommended.

Function:doubleR_atof(const char*str)
Function:doubleR_strtod(const char*str, char **end)

Implementations of the C99/POSIX functionsatof andstrtodwhich guarantee platform- and locale-independent behaviour, includingalways using the period as the decimal pointaka ‘radixcharacter’ and returning R’sNA_REAL_ for all unconvertedstrings, including"NA".

There is also the internal function used to expand file names in severalR functions, and called directly bypath.expand.

Function:const char *R_ExpandFileName(const char *fn)

Expand a path namefn by replacing a leading tilde by the user’shome directory (if defined). The precise meaning is platform-specific;it will usually be taken from the environment variableHOME ifthis is defined.

For historical reasons there are Fortran interfaces to functionsD1MACH andI1MACH. These can be called from C code ase.g.F77_CALL(d1mach)(4). Note that these are emulations ofthe original functions by Fox, Hall and Schryer on Netlib athttps://netlib.org/slatec/src/ forIEC 60559 arithmetic(required by R).


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.11 Re-encoding

R has its own C-level interface to the encoding conversioncapabilities provided byiconv because there areincompatibilities between the declarations in different implementationsoficonv.

These are declared in header fileR_ext/Riconv.h.

Function:void *Riconv_open(const char *to, const char *from)

Set up a pointer to an encoding object to be used to convert between twoencodings:"" indicates the current locale.

Function:size_tRiconv(void *cd, const char **inbuf, size_t *inbytesleft, char **outbuf, size_t *outbytesleft)

Convert as much as possible ofinbuf tooutbuf. Initiallythesize_t variables indicate the number of bytes available in thebuffers, and they are updated (and thechar pointers are updatedto point to the next free byte in the buffer). The return value is thenumber of characters converted, or(size_t)-1 (beware:size_t is usually an unsigned type). It should be safe to assumethat an error condition setserrno to one ofE2BIG (theoutput buffer is full),EILSEQ (the input cannot be converted,and might be invalid in the encoding specified) orEINVAL (theinput does not end with a complete multi-byte character).

Function:intRiconv_close(void *cd)

Free the resources of an encoding object.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.12 Condition handling and cleanup code

Three functions are available for establishing condition handlers fromwithin C code:

#include <Rinternals.h>SEXP R_tryCatchError(SEXP (*fun)(void *data), void *data,                     SEXP (*hndlr)(SEXP cond, void *hdata), void *hdata);SEXP R_tryCatch(SEXP (*fun)(void *data), void *data,                SEXP,                SEXP (*hndlr)(SEXP cond, void *hdata), void *hdata,                void (*clean)(void *cdata), void *cdata);SEXP R_withCallingErrorHandler(SEXP (*fun)(void *data), void *data,                               SEXP (*hndlr)(SEXP cond, void *hdata), void *hdata)

R_tryCatchError establishes an exiting handler for conditionsinheriting form classerror.

R_tryCatch can be used to establish a handler for otherconditions and to register a cleanup action. The conditions to behandled are specified as a character vector (STRSXP).ANULL pointer can be passed asfun orcleanif condition handling or cleanup are not needed.

These are currently implemented using the R-leveltryCatchmechanism so are subject to some overhead.

R_withCallingErrorHandler establishes a calling handler forconditions inheriting from classerror. It establishes thehandler without calling back into R and will therefore be moreefficient.

The functionR_UnwindProtect can be used to ensure that a cleanupaction takes place on ordinary return as well as on a non-local transferof control, which R implements as alongjmp.

SEXP R_UnwindProtect(SEXP (*fun)(void *data), void *data,                     void (*clean)(void *data, Rboolean jump), void *cdata,                     SEXP cont);

R_UnwindProtect can be used in two ways. The simper usage,suitable for use in C code, passesNULL for thecontargument.R_UnwindProtect will callfun(data). Iffun returns a value, thenR_UnwindProtect callsclean(cleandata, FALSE) before returning the value returned byfun. Iffun executes a non-local transfer of control, thenclean(cleandata, TRUE) is called, and the non-local transfer ofcontrol is resumed.

The second use pattern, suitable to support C++ stack unwinding, usestwo additional functions:

SEXP R_MakeUnwindCont();NORET void R_ContinueUnwind(SEXP cont);

R_MakeUnwindCont allocates acontinuation tokencont to pass toR_UnwindProtect. This token should beprotected withPROTECT before callingR_UnwindProtect. When theclean function is called withjump == TRUE, indicating that R is executing a non-local transferof control, it can throw a C++ exception to a C++catch outsidethe C++ code to be unwound, and then use the continuation token in the acallR_ContinueUnwind(cont) to resume the non-local transfer ofcontrol within R.

An older interface for the simplerR_MakeUnwindCont usage remainsavailable:

SEXP R_ExecWithCleanup(SEXP (*fun)(void *), void *data,                       void (*cleanfun)(void *), void *cleandata);

cleanfun is called on both regular returns and non-localtransfers of control, but without an indication of which form of exit isoccurring.

The functionR_ToplevelExec can be used to execute code withoutallowing any non-local transfers of control, including by userinterrupts or invokingabort restarts.

Rboolean R_ToplevelExec(void (*fun)(void *), void *data);

The return value isTRUE iffun returns normally andFALSE iffun exits with a jump to top level.funis called with a new top-level context. Condition handlers and otherfeatures of the current top level context whenR_ToplevelExec iscalled will not be seen by the code infun. Two conveniencefunctions built onR_ToplevelExec areR_tryEval andR_tryEvalSilent.

SEXP R_tryEval(SEXP e, SEXP env, int *ErrorOccurred);SEXP R_tryEvalSilent(SEXP e, SEXP env, int *ErrorOccurred)

These return aNULL pointer if evaluating the expression resultsin a jump to top level.

UsingR_ToplevelExec is usually only appropriate in situationswhere one might want to run code in a separate thread if that was anoption. For example, finalizers are run in a separate top levelcontext. The other functions mentioned in this section will usually bemore appropriate choices.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.13 Allowing interrupts

No part of R can be interrupted whilst running long computations incompiled code, so programmers should make provision for the code to beinterrupted at suitable points by calling from C

#include <R_ext/Utils.h>void R_CheckUserInterrupt(void);

and from Fortran

subroutine rchkusr()

These check if the user has requested an interrupt, and if so branch toR’s error signaling functions.

Note that it is possible that the code behind one of the entry pointsdefined here if called from your C or Fortran code could be interruptibleor generate an error and so not return to your code.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.14 C stack checking

R provides a framework for detecting when the amount of C stack istoo low. Two functions are available:

void R_CheckStack(void)void R_CheckStack2(size_t extra)

These functions signal an error when a low stack condition is detected.R_CheckStack2 does so whenextra bytes are more than isavailable on the stack.

This mechanism is not always available (SeeThreading issues) and itis best to avoid deep recursions in C and to track recursion depth whenusing recursion is unavoidable. C compilers will often optimize tailrecursions to avoid consuming C stack, so it is best to write code in atail-recursive form when possible.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.15 Custom serialization input and output

The internal serialization code uses a framework for serializing from andto different output media. This framework has been in use internally forsome time, but its use in packages is highly experimental and may needto be changed or dropped once some experience is gained. Package authorsconsidering using this framework should keep this in mind.

Client code will define a persistent stream structure with declarationslike

struct R_outpstream_st out;struct R_inpstream_st in;

These are filled in by calling these functions with appropriate arguments:

void R_InitInPStream(R_inpstream_t stream, R_pstream_data_t data,                     R_pstream_format_t type,                     int (*inchar)(R_inpstream_t),                     void (*inbytes)(R_inpstream_t, void *, int),                     SEXP (*phook)(SEXP, SEXP), SEXP pdata);void R_InitOutPStream(R_outpstream_t stream, R_pstream_data_t data,                      R_pstream_format_t type, int version,                      void (*outchar)(R_outpstream_t, int),                      void (*outbytes)(R_outpstream_t, void *, int),                      SEXP (*phook)(SEXP, SEXP), SEXP pdata);

Code should not depend on the fields of the stream structures. Simplerinitializers are available for serializing to or from a file pointer:

void R_InitFileOutPStream(R_outpstream_t stream, FILE *fp,                          R_pstream_format_t type, int version,                          SEXP (*phook)(SEXP, SEXP), SEXP pdata);void R_InitFileInPStream(R_inpstream_t stream, FILE *fp,                         R_pstream_format_t type,                         SEXP (*phook)(SEXP, SEXP), SEXP pdata);

Once the stream structures are set up they can be used by calling

void R_Serialize(SEXP s, R_outpstream_t stream)SEXP R_Unserialize(R_inpstream_t stream)

Examples can be found in the R sources insrc/main/serialize.c.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.16 Platform and version information

The header files defineUSING_R, which can be used to test ifthe code is indeed being used with R.

Header fileRconfig.h (included byR.h) is used to defineplatform-specific macros that are mainly for use in other header files.The macroWORDS_BIGENDIAN is defined onbig-endian172systems (e.g. most OSes on Sparc and PowerPC hardware) and not onlittle-endian systems (nowadays all the commoner R platforms). Itcan be useful when manipulating binary files. NB: these macros applyonly to the C compiler used to build R, not necessarily to another Cor C++ compiler.

Header fileRversion.h (not included byR.h)defines a macroR_VERSION giving the version number encoded as aninteger, plus a macroR_Version to do the encoding. This can beused to test if the version of R is late enough, or to includeback-compatibility features. For protection against very old versionsof R which did not have this macro, use a construction such as

#if defined(R_VERSION) && R_VERSION >= R_Version(3, 1, 0)  ...#endif

More detailed information is available in the macrosR_MAJOR,R_MINOR,R_YEAR,R_MONTH andR_DAY: see theheader fileRversion.h for their format. Note that the minorversion includes the patch level (as in ‘2.2’).

Packages which usealloca need to ensure it is defined: as it ispart of neither C nor POSIX there is no standard way to do so. One canuse

#include <Rconfig.h> // for HAVE_ALLOCA_H#ifdef __GNUC__// this covers gcc, clang, icc# undef alloca# define alloca(x) __builtin_alloca((x))#elif defined(HAVE_ALLOCA_H)// needed for native compilers on Solaris and AIX# include <alloca.h>#endif

(and this should be included before standard C headers such asstdlib.h, since on some platforms these includemalloc.hwhich may have a conflicting definition), which suffices for known Rplatforms.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.17 Inlining C functions

The C99 keywordinline should be recognized by all compilersnowadays used to build R. Portable code which might be used withearlier versions of R can be written using the macroR_INLINE(defined in fileRconfig.h included byR.h), as forexample from packagecluster

#include <R.h>static R_INLINE int ind_2(int l, int j){...}

Be aware that using inlining with functions in more than one compilationunit is almost impossible to do portably, seehttps://www.greenend.org.uk/rjk/tech/inline.html, so this usageis forstatic functions as in the example. All the Rconfigure code has checked is thatR_INLINE can be used in asingle C file with the compiler used to build R. We recommend thatpackages making extensive use of inlining include their own configurecode.


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.18 Controlling visibility

HeaderR_ext/Visibility.h has some definitions for controllingthe visibility of entry points. These are only effective when‘HAVE_VISIBILITY_ATTRIBUTE’ is defined – this is checked when Ris configured and recorded in headerRconfig.h (included byR_ext/Visibility.h). It is often defined on modern Unix-alikeswith a recent compiler173 but not supported on Windows.Minimizing the visibility of symbols in a shared library will both speedup its loading (unlikely to be significant) and reduce the possibilityof linking to other entry points of the same name.

C/C++ entry points prefixed byattribute_hidden will not bevisible in the shared object. There is no comparable mechanism forFortran entry points, but there is a more comprehensive scheme used by,for example packagestats. Most compilers which allow control ofvisibility will allow control of visibility for all symbolsvia aflag, and where known the flag is encapsulated in the macros‘C_VISIBILITY’, ‘CXX_VISIBILITY174 and ‘F_VISIBILITY’ for C, C++ and Fortrancompilers.175These are defined inetc/Makeconf and so available for normalcompilation of package code. For example,src/Makevars couldinclude some of

PKG_CFLAGS=$(C_VISIBILITY)PKG_CXXFLAGS=$(CXX_VISIBILITY)PKG_FFLAGS=$(F_VISIBILITY)

This would end up withno visible entry points, which would bepointless. However, the effect of the flags can be overridden by usingtheattribute_visible prefix. A shared object which registersits entry points needs only for have one visible entry point, itsinitializer, so for example packagestats has

void attribute_visible R_init_stats(DllInfo *dll){    R_registerRoutines(dll, CEntries, CallEntries, FortEntries, NULL);    R_useDynamicSymbols(dll, FALSE);...}

Because the ‘C_VISIBILITY’ mechanism is only useful in conjunctionwithattribute_visible, it is not enabled unless‘HAVE_VISIBILITY_ATTRIBUTE’ is defined. The usual visibility flagis-fvisibility=hidden: some compilers also support-fvisibility-inlines-hidden which can be used by overriding‘C_VISIBILITY’ and ‘CXX_VISIBILITY’ inconfig.site whenbuilding R, or editingetc/Makeconf in the R installation.

Note thatconfigure only checks that visibility attributes andflags are accepted, not that they actually hide symbols.

The visibility mechanism is not available on Windows, but there is anequally effective way to control which entry points are visible, bysupplying a definitions filepkgname/src/pkgname-win.def: only entry pointslisted in that file will be visible. Again usingstats as anexample, it has

LIBRARY stats.dllEXPORTS R_init_stats

Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.19 Using these functions in your own C code

It is possible to buildMathlib, the R set of mathematicalfunctions documented inRmath.h, as a standalone librarylibRmath under both Unix-alikes and Windows. (This includes thefunctions documented inNumerical analysis subroutines as fromthat header file.)

The library is not built automatically when R is installed. Forfurther details including how to build it, seeThe standalone Rmath library inR Installation and Administration.

To use the code in your own C program include

#define MATHLIB_STANDALONE#include <Rmath.h>

and link against ‘-lRmath’ (and perhaps ‘-lm’). There is anexample filetest.c.

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

double unif_rand(void)

or use the one supplied (and with a dynamic library or DLL you will haveto use the one supplied, which is the Marsaglia-multicarry with an entrypoints

set_seed(unsigned int, unsigned int)

to set its seeds and

get_seed(unsigned int *, unsigned int *)

to read the seeds).


Next:, Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.20 Organization of header files

The header files which R installs are in directoryR_INCLUDE_DIR (defaultR_HOME/include). Thiscurrently includes

R.hincludes many other files
Rinternals.hdefinitions for using R’s internalstructures
Rdefines.hmacros for an S-like interface to theabove (no longer maintained)
Rmath.hstandalone math library
Rversion.hR version information
Rinterface.hfor add-on front-ends (Unix-alikes only)
Rembedded.hfor add-on front-ends
R_ext/Applic.hoptimization, integration and some LAPACK ones)
R_ext/BLAS.hC definitions for BLAS routines
R_ext/Callbacks.hC (and R function) top-level taskhandlers
R_ext/GetX11Image.hX11Image interface used by packagetrkplot
R_ext/Lapack.hC definitions for some LAPACK routines
R_ext/Linpack.hC definitions for some LINPACKroutines, not all of which are included in R
R_ext/Parse.ha small part of R’s parse interface:not part of the stable API.
R_ext/RStartup.hfor add-on front-ends
R_ext/Rdynload.hneeded to register compiled code inpackages
R_ext/Riconv.hinterface toiconv
R_ext/Visibility.hdefinitions controlling visibility
R_ext/eventloop.hfor add-on front-ends and forpackages that need to share in the R event loops (not Windows)

The following headers are included byR.h:

Rconfig.hconfiguration info that is made available
R_ext/Arith.hhandling forNAs,NaNs,Inf/-Inf
R_ext/Boolean.hTRUE/FALSE type
R_ext/Complex.hC typedefs for R’scomplex
R_ext/Constants.hconstants
R_ext/Error.herror signaling
R_ext/Memory.hmemory allocation
R_ext/Print.hRprintf and variations.
R_ext/RS.hdefinitions common toR.h and the formerS.h, includingF77_CALL etc.
R_ext/Random.hrandom number generation
R_ext/Utils.hsorting and other utilities
R_ext/libextern.hdefinitions for exports fromR.dll on Windows.

The graphics systems are exposed in headersR_ext/GraphicsEngine.h,R_ext/GraphicsDevice.h (which itincludes) andR_ext/QuartzDevice.h. Facilities for definingcustom connection implementations are provided inR_ext/Connections.h, but make sure you consult the file beforeuse.

Let us re-iterate the advice to include in C++ code system headersbefore the R header files, especiallyRinternals.h (includedbyRdefines.h) andRmath.h, which redefine names which maybe used in system headers, or (preferably and the default since R4.5.0) to defineR_NO_REMAP.


Previous:, Up:The RAPI: entry points for C code   [Contents][Index]

6.21 Moving into C API compliance

Work is in progress to clarify and tighten the C API for extending Rcode. This will help make package C code more robust, and willfacilitate maintaining and improving the R source code without impactingpackage space. In the process a number of entry points intended forinternal use will be removed from installed header files or hidden, andothers will be replaced by more robust versions better suited for use inpackage C code. This section describes how packages can move from usingnon-API entry points to using ones available and supported in the API.

Work in progress: This section is a work in progress and willbe adjusted as changes are made to the API.


Next:, Up:Moving into C API compliance   [Contents][Index]

6.21.1 Some API replacements for non-API entry points

Some non-API entry points intended for internal use have long had entrypoints in the API that can be used instead. In other cases new entrypoint have been added that are more appropriate for use in packages;typically these include more extensive error checking on arguments.

This table lists some non-API functions used in packages and the APIfunctions that should be used instead:

EXTPTR_PROT
EXTPTR_TAG
EXTPTR_PTR

UseR_ExternalPtrProtected,R_ExternalPtrTag, andR_ExternalPtrAddr.

OBJECT
IS_S4_OBJECT

UseRf_isObject andRf_isS4.

GetOption

UseRf_GetOption1.

R_lsInternal

UseR_lsInternal3.

REAL0
COMPLEX0

UseREAL andCOMPLEX.

STRING_PTR
DATAPTR
STDVEC_DATAPTR

UseSTRING_PTR_RO andDATAPTR_RO. Obtaining writable pointers to these data can violate the memory manager’s integrity assumptions and is not supported.

isFrame

UseRf_isDataFrame, added in R 4.5.0.

BODY
FORMALS
CLOENV

UseR_ClosureBody,R_ClosureFormals, andR_ClosureEnv; these were added in R 4.5.0.

ENCLOS

UseR_ParentEnv, added in R 4.5.0.

IS_ASCII

UseRf_charIsASCII, added in R 4.5.0.

IS_UTF8

UsecharIsUTF8, added in R 4.5.0, or avoid completely.

Rf_allocSExp

Use an appropriate constructor.

Rf_findVarInFrame3

UseR_existsVarInFrame to test for existence.

Rf_findVar
Rf_findVarInFrame

UseR_getVar orR_getVarEx, added in R 4.5.0. In some cases usingeval may suffice.

ATTRIB

UseRf_getAttrib for individual attributes. To test whether there are any attributes useANY_ATTRIB, added in R 4.5.0.

SET_ATTRIB
SET_OBJECT

UseRf_setAttrib for individual attributes,DUPLICATE_ATTRIB orSHALLOW_DUPLICATE_ATTRIB for copying attributes from one object to another. UseCLEAR_ATTRIB for removing all attributes, added in R 4.5.0.

R_GetCurrentEnv

Useenvironment() at the R level and pass the result as an argument to your C function.

For recently added entry points packages that need to be compiledunder older versions that do not yet contain these entry points canuse back-ported versions defined conditionally. SeeSome backports.


Next:, Previous:, Up:Moving into C API compliance   [Contents][Index]

6.21.2 Creating environments

An idiom appearing in a number of packages is to create an environmentas

SEXP env = Rf_allocSExp(ENVSXP);SET_ENCLOS(env, parent);

The functionRf_allocSExp and mutation functions likeSET_ENCLOS,SET_FRAME, andSET_HASHTAB are not partof the API as they expose internal structure that might need to changein the future. A proper constructor function should be usedinstead. The constructor function for environments isR_NewEnv,so the new environment should be created as

SEXP env = R_NewEnv(parent, FALSE, 0);

Next:, Previous:, Up:Moving into C API compliance   [Contents][Index]

6.21.3 Creating call expressions

Another idiom used in some packages is to create a call expression withspace for two arguments as

SEXP expr = Rf_allocList(3);SET_TYPEOF(expr, "LANGSXP");

and then fill in the function and argument expressions.SET_TYPEOF will also not be available to packages in thefuture. An alternative way to construct the expression that will work inany R version is

SEXP expr = LCONS(R_NilValue, allocList(2));

R 4.4.1 added the constructorRf_allocLang, so the expressioncan be created as

SEXP env = Rf_allocLang(3);

Next:, Previous:, Up:Moving into C API compliance   [Contents][Index]

6.21.4 Creating closures

Yet another common idiom is to create a new closure as

SEXP fun = Rf_allocSExp(CLOSXP);SET_FORMALS(fun, formals);SET_BODY(fun, body);SET_CLOENV(fun, env);

R 4.5.0 adds the constructorR_mkClosure; this can be used as

SEXP fun = R_mkClosure(formals, body, env);

Next:, Previous:, Up:Moving into C API compliance   [Contents][Index]

6.21.5 QueryingCHARSXP encoding

A number of packages query encoding bits set onCHARSXP objects via macrosIS_ASCII andIS_UTF8, some packages also viaIS_BYTESandIS_LATIN1. These macros are not part of the API and packageshave been copying their definition and directly accessing the bits inmemory. The structure of the object header is, however, internal to R andmay have to change in the future.

IS_ASCII can be replaced byRf_charIsASCII, added in R 4.5.0.It can also be replaced by code that checks individual characters (bytes).

Information provided by the other macros is available via functionRf_getCharCE, which has been part of the API since R 2.7.0.Before switching toRf_getCharCE, packages are, however, advisedto check whether the encoding information is really needed and whetherit is used correctly.

Most code should be able to work with completeCHARSXPs and never look atthe individual bytes. When access to characters and bytes (of strings otherthanCE_BYTES) is needed, one would useRf_translateChar orRf_translateCharUTF8. These functions internally already check theencoding and whether the string is ASCII and only translate when needed,which should be rarely since R >= 4.2.0 (UTF-8 is used as native encodingon most systems running R).

Several packages use the encoding information to find out whether aninternal string representation visible viaCHAR is UTF-8 orlatin1. R 4.5.0 provides functionsRf_charIsUTF8 andRf_charIsLatin1 for this purpose, which are safer against futurechanges and handle also native strings when running in the correspondinglocale. Note that both will be true for ASCII strings.

A pattern used in several packages is

char *asutf8(SEXP c){  if (!IS_UTF8(s) && !IS_ASCII(s))  // not compliant    return Rf_translateCharUTF8(s);   else    return CHAR(s);}

to make this code compliant, simply call

char *asutf8(SEXP c){  return Rf_translateCharUTF8(s); // compliant}

as the encoding flags are already checked inRf_translateCharUTF8. Alsonote the non-compliant check does not handle native encoding.


Next:, Previous:, Up:Moving into C API compliance   [Contents][Index]

6.21.6 Working with attributes

The current implementation (R 4.5.0) represents attributes internallyas a linked list. It may be useful to change this at some point, soexternal code should not rely on this representation. The low-levelfunctionsATTRIB andSET_ATTRIB reveal this representationand are therefore not part of the API. Individual attributes can beaccessed and set withRf_getAttrib andRf_setAttrib. Attributescan be copied from one object to another withDUPLICATE_ATTRIBandSHALLOW_DUPLICATE_ATTRIB. TheCLEAR_ATTRIB functionadded in R 4.5.0 can be used to remove all attributes. Thesefunctions ensure can that certain consistency requirements aremaintained, such as setting the object bit according to whether a classattribute is present.

Some additional functions may be added for working with attributes.


Next:, Previous:, Up:Moving into C API compliance   [Contents][Index]

6.21.7 Working variable bindings

The functionsRf_findVar andRf_findVarInFrame have been used ina number of packages but are too low level to be part of the API. Formost uses the functionsR_getVar andR_getVarEx added inR 4.5.0 will be sufficient. These are analogous to the R functionsget andget0.

In rare cases package R or C code may want to obtain more detailedinformation on a binding, such as whether the binding is delayed ornot. This is currently not possible within the API, but is underconsideration.


Previous:, Up:Moving into C API compliance   [Contents][Index]

6.21.8 Some backports

This section lists backports of recently added definitions that can beused in packages that need to be compiled under older versions of Rthat do not yet contain these entry points.

#if R_VERSION < R_Version(4, 4, 1)#define allocLang Rf_allocLangSEXP Rf_allocLang(int n){    if (n > 0)          return LCONS(R_NilValue, Rf_allocList(n - 1));    else          return R_NilValue;}#endif#if R_VERSION < R_Version(4, 5, 0)# define isDataFrame(x) Rf_isFrame(x)# define R_ClosureFormals(x) FORMALS(x)# define R_ClosureEnv(x) CLOENV(x)# define R_ParentEnv(x) ENCLOS(x)SEXP R_mkClosure(SEXP formals, SEXP body, SEXP env){    SEXP fun = Rf_allocSExp(CLOSXP);    SET_FORMALS(fun, formals);    SET_BODY(fun, body);    SET_CLOENV(fun, env);    return fun;}void CLEAR_ATTRIB(SEXP x){    SET_ATTRIB(x, R_NilValue);    SET_OBJECT(x, 0);    UNSET_S4_OBJECT(x);}#endif

Next:, Previous:API: entry points for C code, Up:Writing R Extensions   [Contents][Index]

7 Generic functions and methods

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

This chapter only covers the ‘informal’ class system copied from S3,and not with the S4 (formal) methods of packagemethods.

First, acaveat: a function namedgen.cl willbe invoked by the genericgen for classcl, sodo not name functions in this style unless they are intended to bemethods.

The key function for methods isNextMethod, which dispatches thenext method. It is quite typical for a method function to make a fewchanges to its arguments, dispatch to the next method, receive theresults and modify them a little. An example is

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

Note that the example above works because there is anext method,the default method, not that a new method is selected when the class ischanged.

Any method a programmer writes may be invoked from another methodbyNextMethod,with the arguments appropriate to theprevious method. Further, the programmer cannot predict which methodNextMethod will pick (it might be one not yet dreamt of), and theend user calling the generic needs to be able to pass arguments to thenext method. For this to work

A method must have all the arguments of the generic, including if the generic does.

It is a grave misunderstanding to think that a method needs only toaccept the arguments it needs. The original S version ofpredict.lm did not have a argument, althoughpredict did. It soon became clear thatpredict.glm neededan argumentdispersion to handle over-dispersion. Aspredict.lm had neither adispersion nor aargument,NextMethod could no longer be used. (The legacy, twodirect calls topredict.lm, lives on inpredict.glm inR, which is based on the workaround for S3 written by Venables &Ripley.)

Further, the user is entitled to use positional matching when callingthe generic, and the arguments to a method called byUseMethodare those of the call to the generic. Thus

A method must have arguments in exactly the same order as thegeneric.

To see the scale of this problem, consider the generic functionscale, defined as

scale <- function (x, center = TRUE, scale = TRUE)    UseMethod("scale")

Suppose an unthinking package writer created methods such as

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

Then forx of class"foo" the calls

scale(x, , TRUE)scale(x, scale = TRUE)

would most likely do different things, to the justifiableconsternation of the end user.

To add a further twist, which default is used when a user callsscale(x) in our example? What if

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

andx has classc("bar", "foo")? It is the defaultspecified in the method that is used, but the defaultspecified in the generic may be the one the user sees.This leads to the recommendation:

If the generic specifies defaults, all methods should use the same defaults.

An easy way to follow these recommendations is to always keep genericssimple, e.g.

scale <- function(x, ...) UseMethod("scale")

Only add parameters and defaults to the generic if they make sense inall possible methods implementing it.


Up:Generic functions and methods   [Contents][Index]

7.1 Adding new generics

When creating a new generic function, bear in mind that its argumentlist will be the maximal set of arguments for methods, including thosewritten elsewhere years later. So choosing a good set of arguments maywell be an important design issue, and there need to be good argumentsnot to include a argument.

If a argument is supplied, some thought should be givento its position in the argument sequence. Arguments which follow must be named in calls to the function, and they must benamed in full (partial matching is suppressed after).Formal arguments before can be partially matched, and somay ‘swallow’ actual arguments intended for. Although itis commonplace to make the argument the last one, that isnot always the right choice.

Sometimes package writers want to make generic a function in the basepackage, and request a change in R. This may be justifiable, butmaking a function generic with the old definition as the default methoddoes have a small performance cost. It is never necessary, as a packagecan take over a function in the base package and make it generic bysomething like

foo <- function(object, ...) UseMethod("foo")foo.default <- function(object, ...) base::foo(object)

Earlier versions of this manual suggested assigningfoo.default <-base::foo. This isnot a good idea, as it captures the basefunction at the time of installation and it might be changed as R ispatched or updated.

The same idea can be applied for functions in other packages.


Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

8 Linking GUIs and other front-ends to R

There are a number of ways to build front-ends to R: we take this tomean a GUI or other application that has the ability to submit commandsto R and perhaps to receive results back (not necessarily in a textformat). There are other routes besides those described here, forexample the packageRserve (fromCRAN, see alsohttps://www.rforge.net/Rserve/) and connections to Java in‘JRI’ (part of therJava package onCRAN).

Note that theAPIs described in this chapter are only intended to beused in an alternative front-end: they are not part of the API madeavailable for R packages and can be dangerous to use in aconventional package (although packages may contain alternativefront-ends). Conversely some of the functions from the API (such asR_alloc) should not be used in front-ends.


Next:, Up:Linking GUIs and other front-ends to R   [Contents][Index]

8.1 Embedding R under Unix-alikes

R can be built as a shared library176 if configured with--enable-R-shlib. Thisshared library can be used to run R from alternative front-endprograms. We will assume this has been done for the rest of thissection. Also, it can be built as a static library if configured with--enable-R-static-lib, and that can be used in a very similarway (at least on Linux: on other platforms one needs to ensure that allthe symbols exported bylibR.a are linked into the front-end).

The command-line R front-end,R_HOME/bin/exec/R, is onesuch example, and the formerGNOME (see packagegnomeGUIonCRAN’s ‘Archive’ area) and macOS consoles are others.The source forR_HOME/bin/exec/R is in filesrc/main/Rmain.c and is very simple

int Rf_initialize_R(int ac, char **av); /* in ../unix/system.c */void Rf_mainloop();                     /* in main.c */extern int R_running_as_main_program;   /* in ../unix/system.c */int main(int ac, char **av){    R_running_as_main_program = 1;    Rf_initialize_R(ac, av);    Rf_mainloop(); /* does not return */    return 0;}

indeed, misleadingly simple. Remember thatR_HOME/bin/exec/R is run from a shell scriptR_HOME/bin/R which sets up the environment for theexecutable, and this is used for

  • SettingR_HOME and checking it is valid, as well as the pathR_SHARE_DIR andR_DOC_DIR to the installedshare anddoc directory trees. Also settingR_ARCH if needed.
  • SettingLD_LIBRARY_PATH to include the directories used in linkingR. This is recorded as the default setting ofR_LD_LIBRARY_PATH in the shell scriptR_HOME/etcR_ARCH/ldpaths.
  • Processing some of the arguments, for example to run R under adebugger and to launch alternative front-ends to provide GUIs.

The first two of these can be achieved for your front-end by running itviaR CMD. So, for example

R CMD /usr/local/lib/R/bin/exec/RR CMD exec/R

will both work in a standard R installation. (R CMD looksfirst for executables inR_HOME/bin. These command-linesneed modification if a sub-architecture is in use.) If you do not wantto run your front-end in this way, you need to ensure thatR_HOMEis set andLD_LIBRARY_PATH is suitable. (The latter might wellbe, but modern Unix/Linux systems do not normally include/usr/local/lib (/usr/local/lib64 on some architectures),and R does look there for system components.)

The other senses in which this example is too simple are that all theinternal defaults are used and that control is handed over to theR main loop. There are a number of small examples177 in thetests/Embedding directory. These make use ofRf_initEmbeddedR insrc/main/Rembedded.c, and essentiallyuse

#include <Rembedded.h>int main(int ac, char **av){    /* do some setup */    Rf_initEmbeddedR(argc, argv);    /* do some more setup */    /* submit some code to R, which is done interactively via        run_Rmainloop();        A possible substitute for a pseudo-console is        R_ReplDLLinit();        while(R_ReplDLLdo1() > 0) {        /* add user actions here if desired */       }     */    Rf_endEmbeddedR(0);    /* final tidying up after R is shutdown */    return 0;}

If you do not want to pass R arguments, you can fake anargvarray, for example by

    char *argv[]= {"REmbeddedPostgres", "--silent"};    Rf_initEmbeddedR(sizeof(argv)/sizeof(argv[0]), argv);

However, to make a GUI we usually do want to runrun_Rmainloopafter setting up various parts of R to talk to our GUI, and arrangingfor our GUI callbacks to be called during the R mainloop.

One issue to watch is that on some platformsRf_initEmbeddedR andRf_endEmbeddedR change the settings of theFPU (e.g. to allowerrors to be trapped and to make use of extended precision registers).

The standard code sets up a session temporary directory in the usualway,unlessR_TempDir is set to a non-NULL value beforeRf_initEmbeddedR is called. In that case the value is assumed tocontain an existing writable directory, and it is notcleaned up when R is shut down.

Rf_initEmbeddedR sets R to be in interactive mode: you can setR_Interactive (defined inRinterface.h) subsequently tochange this.

Note that R expects to be run with the locale category‘LC_NUMERIC’ set to its default value ofC, and so shouldnot be embedded into an application which changes that.

It is the user’s responsibility to attempt to initialize only once. Toprotect the R interpreter,Rf_initialize_R will exit theprocess if re-initialization is attempted.


Next:, Up:Embedding R under Unix-alikes   [Contents][Index]

8.1.1 Compiling against the R library

Suitable flags to compile and link against the R (shared or static)library can be found by

R CMD config --cppflagsR CMD config --ldflags

(These apply only to an uninstalled copy or a standard install.)

If R is installed,pkg-config is available and neithersub-architectures nor a macOS framework have been used, alternatives fora shared R library are

pkg-config --cflags libRpkg-config --libs libR

and for a static R library

pkg-config --cflags libRpkg-config --static --libs libR

(This may work for an installed OS framework ifpkg-config istaught where to look forlibR.pc: it is installed inside theframework.)

However, a more comprehensive way is to set up aMakefile tocompile the front-end. Suppose filemyfe.c is to be compiled tomyfe. A suitableMakefile might be

## WARNING: does not work when ${R_HOME} contains spacesinclude ${R_HOME}/etc${R_ARCH}/Makeconfall: myfe## The following is not needed, but avoids PIC flags.myfe.o: myfe.c        $(CC) $(ALL_CPPFLAGS) $(CFLAGS) -c myfe.c -o $@## replace $(LIBR) $(LIBS) by $(STATIC_LIBR) if R was built with a static libRmyfe: myfe.o        $(MAIN_LINK) -o $@ myfe.o $(LIBR) $(LIBS)

invoked as

R CMD makeR CMD myfe

Even though not recommended,${R_HOME} may contain spaces. Inthat case, it cannot be passed as an argument toinclude in themakefile. Instead, one can instructmake using the-foption to includeMakeconf, for examplevia recursiveinvocation ofmake, seeWriting portable packages.

all:      $(MAKE) -f "${R_HOME}/etc${R_ARCH}/Makeconf" -f Makefile.inner

Additional flags which$(MAIN_LINK) includes are, amongst others,those to selectOpenMP and--export-dynamic for the GNU linkeron some platforms. In principle$(LIBS) is not neededwhen using a shared R library aslibR is linked againstthose libraries, but some platforms need the executable also linkedagainst them.


Next:, Previous:, Up:Embedding R under Unix-alikes   [Contents][Index]

8.1.2 Setting R callbacks

For Unix-alikes there is a public header fileRinterface.h thatmakes it possible to change the standard callbacks used by R in adocumented way. This defines pointers (ifR_INTERFACE_PTRS isdefined)

extern void (*ptr_R_Suicide)(const char *);extern void (*ptr_R_ShowMessage)(const char *);extern int  (*ptr_R_ReadConsole)(const char *, unsigned char *, int, int);extern void (*ptr_R_WriteConsole)(const char *, int);extern void (*ptr_R_WriteConsoleEx)(const char *, int, int);extern void (*ptr_R_ResetConsole)();extern void (*ptr_R_FlushConsole)();extern void (*ptr_R_ClearerrConsole)();extern void (*ptr_R_Busy)(int);extern void (*ptr_R_CleanUp)(SA_TYPE, int, int);extern int  (*ptr_R_ShowFiles)(int, const char **, const char **,                               const char *, Rboolean, const char *);extern int  (*ptr_R_ChooseFile)(int, char *, int);extern int  (*ptr_R_EditFile)(const char *);extern void (*ptr_R_loadhistory)(SEXP, SEXP, SEXP, SEXP);extern void (*ptr_R_savehistory)(SEXP, SEXP, SEXP, SEXP);extern void (*ptr_R_addhistory)(SEXP, SEXP, SEXP, SEXP);extern int  (*ptr_R_EditFiles)(int, const char **, const char **, const char *);extern SEXP (*ptr_do_selectlist)(SEXP, SEXP, SEXP, SEXP);extern SEXP (*ptr_do_dataentry)(SEXP, SEXP, SEXP, SEXP);extern SEXP (*ptr_do_dataviewer)(SEXP, SEXP, SEXP, SEXP);extern void (*ptr_R_ProcessEvents)();

which allow standard R callbacks to be redirected to your GUI. Whatthese do is generally documented in the filesrc/unix/system.txt.

Function:voidR_ShowMessage(char *message)

This should display the message, which may have multiple lines: itshould be brought to the user’s attention immediately.

Function:voidR_Busy(intwhich)

This function invokes actions (such as change of cursor) when Rembarks on an extended computation (which=1) and when sucha state terminates (which=0).

Function:intR_ReadConsole(const char *prompt, unsigned char *buf, intbuflen, inthist)
Function:voidR_WriteConsole(const char *buf, intbuflen)
Function:voidR_WriteConsoleEx(const char *buf, intbuflen, intotype)
Function:voidR_ResetConsole()
Function:voidR_FlushConsole()
Function:voidR_ClearerrConsole()

These functions interact with a console.

R_ReadConsole prints the given prompt at the console and then does afgets(3)–like operation, writing up tobuflen bytes into thebufferbuf. The last of the bytes written should be ‘"\0"’.When there is enough space in the buffer to hold the full input lineincluding the line terminator, the line terminator should be included.Otherwise, the rest of the line should be returned in subsequent calls toR_ReadConsole. The last call should return data terminated by the lineterminator. Ifhist is non-zero, then the line should be added to anycommand history which is being maintained. The return value is 0 if noinput is available and >0 otherwise.

R_WriteConsoleEx writes the given buffer to the console,otype specifies the output type (regular output orwarning/error). Call toR_WriteConsole(buf, buflen) is equivalenttoR_WriteConsoleEx(buf, buflen, 0). To ensure backwardcompatibility of the callbacks,ptr_R_WriteConsoleEx is used onlyifptr_R_WriteConsole is set toNULL. To ensure thatstdout() andstderr() connections point to the console,set the corresponding files toNULLvia

      R_Outputfile = NULL;      R_Consolefile = NULL;

R_ResetConsole is called when the system is reset after an error.R_FlushConsole is called to flush any pending output to thesystem console.R_ClearerrConsole clears any errors associatedwith reading from the console.

Function:intR_ShowFiles(intnfile, const char **file, const char **headers, const char *wtitle, Rbooleandel, const char *pager)

This function is used to display the contents of files.

Function:intR_ChooseFile(intnew, char *buf, intlen)

Choose a file and return its name inbuf of lengthlen.Return value is 0 for success, > 0 otherwise.

Function:intR_EditFile(const char *buf)

Send a file to an editor window.

Function:intR_EditFiles(intnfile, const char **file, const char **title, const char *editor)

Sendnfile files to an editor, with titles possibly to be used forthe editor window(s).

Function:SEXPR_loadhistory(SEXP, SEXP, SEXP, SEXP);
Function:SEXPR_savehistory(SEXP, SEXP, SEXP, SEXP);
Function:SEXPR_addhistory(SEXP, SEXP, SEXP, SEXP);

.Internal functions forloadhistory,savehistoryandtimestamp.

If the console has no history mechanism these can be assimple as

SEXP R_loadhistory (SEXP call, SEXP op, SEXP args, SEXP env){    errorcall(call, "loadhistory is not implemented");    return R_NilValue;}SEXP R_savehistory (SEXP call, SEXP op , SEXP args, SEXP env){    errorcall(call, "savehistory is not implemented");    return R_NilValue;}SEXP R_addhistory (SEXP call, SEXP op , SEXP args, SEXP env){    return R_NilValue;}

TheR_addhistory function should return silently if no historymechanism is present, as a user may be callingtimestamp purelyto write the time stamp to the console.

Function:voidR_Suicide(const char *message)

This should abort R as rapidly as possible, displaying the message.A possible implementation is

void R_Suicide (const char *message){    char  pp[1024];    snprintf(pp, 1024, "Fatal error: %s\n", message);    R_ShowMessage(pp);    R_CleanUp(SA_SUICIDE, 2, 0);}
Function:voidR_CleanUp(SA_TYPEsaveact, intstatus, intRunLast)

This function invokes any actions which occur at system termination.It needs to be quite complex:

#include <Rinterface.h>#include <Rembedded.h>    /* for Rf_KillAllDevices */void R_CleanUp (SA_TYPE saveact, int status, int RunLast){    if(saveact == SA_DEFAULT) saveact = SaveAction;    if(saveact == SA_SAVEASK) {       /* ask what to do and set saveact */    }    switch (saveact) {    case SA_SAVE:        if(runLast) R_dot_Last();        if(R_DirtyImage) R_SaveGlobalEnv();        /* save the console history in R_HistoryFile */        break;    case SA_NOSAVE:        if(runLast) R_dot_Last();        break;    case SA_SUICIDE:    default:        break;    }    R_RunExitFinalizers();    /* clean up after the editor e.g. CleanEd() */    R_CleanTempDir();    /* close all the graphics devices */    if(saveact != SA_SUICIDE) Rf_KillAllDevices();    fpu_setup(FALSE);    exit(status);}

These callbacks should never be changed in a running R session (andhence cannot be called from an extension package).

Function:SEXPR_dataentry(SEXP, SEXP, SEXP, SEXP);
Function:SEXPR_dataviewer(SEXP, SEXP, SEXP, SEXP);
Function:SEXPR_selectlist(SEXP, SEXP, SEXP, SEXP);

.External functions fordataentry (andedit onmatrices and data frames),View andselect.list. Thesecan be changed if they are not currently in use.


Next:, Previous:, Up:Embedding R under Unix-alikes   [Contents][Index]

8.1.3 Registering symbols

An application embedding R needs a different way of registeringsymbols because it is not a dynamic library loaded by R as would bethe case with a package. Therefore R reserves a specialDllInfo entry for the embedding application such that it canregister symbols to be used with.C,.Call etc. Thisentry can be obtained by callinggetEmbeddingDllInfo, so atypical use is

DllInfo *info = R_getEmbeddingDllInfo();R_registerRoutines(info, cMethods, callMethods, NULL, NULL);

The native routines defined bycMethods andcallMethodsshould be present in the embedding application. SeeRegistering native routines for details on registering symbols in general.


Next:, Previous:, Up:Embedding R under Unix-alikes   [Contents][Index]

8.1.4 Meshing event loops

One of the most difficult issues in interfacing R to a front-end isthe handling of event loops, at least if a single thread is used. Ruses events and timers for

  • Running X11 windows such as the graphics device and data editor, andinteracting with them (e.g., usinglocator()).
  • Supporting Tcl/Tk events for thetcltk package (for at least theX11 version of Tk).
  • Preparing input.
  • Timing operations, for example for profiling R code andSys.sleep().
  • Interrupts, where permitted.

Specifically, the Unix-alike command-line version of R runs separateevent loops for

  • Preparing input at the console command-line, in filesrc/unix/sys-unix.c.
  • Waiting for a response from a socket in the internal functions fordirect socket access in filesrc/modules/internet/Rsock.cand for the interface tolibcurl.
  • Mouse and window events when displaying the X11-based dataentry window,in filesrc/modules/X11/dataentry.c. This is regarded asmodal, and no other events are serviced whilst it is active.

There is a protocol for adding event handlers to the first two types ofevent loops, using types and functions declared in the headerR_ext/eventloop.h and described in comments in filesrc/unix/sys-std.c. It is possible to add (or remove) an inputhandler for events on a particular file descriptor, or to set a pollinginterval (viaR_wait_usec) and a function to be calledperiodicallyviaR_PolledEvents: the polling mechanism isused by thetcltk package. Input handlers are managed withaddInputHandler,getInputHandler, andremoveInputHandler. The handlers are held in a linked listR_InputHandlers.

It is not intended that these facilities are used by packages, but ifthey are needed exceptionally, the package should ensure that it cleansup and removes its handlers when its namespace is unloaded. Note thatthe headersys/select.h is needed178: users should check this is available and defineHAVE_SYS_SELECT_H before includingR_ext/eventloop.h. (Itis often the case that another header will includesys/select.hbeforeeventloop.h is processed, but this should not be reliedon.)

An alternative front-end needs both to make provision for other Revents whilst waiting for input, and to ensure that it is not frozen outduring events of the second type. The ability to add a polled handlerasR_timeout_handler is used by thetcltk package.


Previous:, Up:Embedding R under Unix-alikes   [Contents][Index]

8.1.5 Threading issues

Embedded R is designed to be run in the main thread, and all thetesting is done in that context. There is a potential issue with thestack-checking mechanism where threads are involved. This uses twovariables declared inRinterface.h (ifCSTACK_DEFNS isdefined) as

extern uintptr_t R_CStackLimit; /* C stack limit */extern uintptr_t R_CStackStart; /* Initial stack address */

Note thatuintptr_t is an optional C99 type for which asubstitute is defined in R, so your code needs to defineHAVE_UINTPTR_T appropriately. To do so, test if the type isdefined in C headerstdint.h or C++ headercstdint and ifso include the header and defineHAVE_UINTPTR_T before includingRinterface.h. (For C code one can simply includeRconfig.h, possiblyviaR.h, and for C++11 codeRinterface.h will include the headercstdint.)

These will be set179 whenRf_initialize_R is called, to values appropriate tothe main thread. Stack-checking can be disabled by settingR_CStackLimit = (uintptr_t)-1 immediately afterRf_initialize_R is called, but it is better to if possible setappropriate values. (What these are and how to determine them areOS-specific, and the stack size limit may differ for secondary threads.If you have a choice of stack size, at least 10Mb is recommended.)

You may also want to consider how signals are handled: R sets signalhandlers for several signals, includingSIGINT,SIGSEGV,SIGPIPE,SIGUSR1 andSIGUSR2, but these can all besuppressed by setting the variableR_SignalHandlers (declared inRinterface.h) to0.

Note that these variables must not be changed by an Rpackage: a package should not call R internals whichmakes use of the stack-checking mechanism on a secondary thread.


Previous:, Up:Linking GUIs and other front-ends to R   [Contents][Index]

8.2 Embedding R under Windows

This section is only about ‘x86_64’ Windows.

All Windows interfaces to R call entry points in the DLLR.dll, directly or indirectly. Simpler applications may find iteasier to use the indirect routevia(D)COM.


Next:, Up:Embedding R under Windows   [Contents][Index]

8.2.1 Using (D)COM

(D)COM is a standard Windows mechanism used for communicationbetween Windows applications. One application (here R) is run as COMserver which offers services to clients, here the front-end callingapplication. The services are described in a ‘Type Library’ and are(more or less) language-independent, so the calling application can bewritten in C or C++ or Visual Basic or Perl or Python and so on.The ‘D’ in (D)COM refers to ‘distributed’, as the client and server canbe running on different machines.

The basic R distribution is not a (D)COM server, but two addons arecurrently available that interface directly with R and provide a(D)COM server:


Next:, Previous:, Up:Embedding R under Windows   [Contents][Index]

8.2.2 CallingR.dll directly

TheR DLL is mainly written in C and has_cdecl entrypoints. Calling it directly will be tricky except from C code (or C++with a little care).

There is a version of the Unix-alike interface calling

int Rf_initEmbeddedR(int ac, char **av);void Rf_endEmbeddedR(int fatal);

which is an entry point inR.dll. Examples of its use (and asuitableMakefile.win) can be found in thetests/Embeddingdirectory of the sources. You may need to ensure thatR_HOME/bin is in yourPATH so the R DLLs are found.

Examples of callingR.dll directly are provided in the directorysrc/gnuwin32/front-ends, including a simple command-linefront endrtest.c whose code is

#define Win32#include <windows.h>#include <stdio.h>#include <Rversion.h>#define LibExtern __declspec(dllimport) extern#include <Rembedded.h>#include <R_ext/RStartup.h>/* for askok and askyesnocancel */#include <graphapp.h>/* for signal-handling code */#include <psignal.h>/* simple input, simple output *//* This version blocks all events: a real one needs to call ProcessEvents   frequently. See rterm.c and ../system.c for one approach using   a separate thread for input.*/int myReadConsole(const char *prompt, unsigned char *buf, int len, int addtohistory){    fputs(prompt, stdout);    fflush(stdout);    if(fgets((char *)buf, len, stdin)) return 1; else return 0;}void myWriteConsole(const char *buf, int len){    printf("%s", buf);}void myCallBack(void){    /* called during i/o, eval, graphics in ProcessEvents */}void myBusy(int which){    /* set a busy cursor ... if which = 1, unset if which = 0 */}static void my_onintr(int sig) { UserBreak = 1; }int main (int argc, char **argv){    structRstart rp;    Rstart Rp = &rp;    char Rversion[25], *RHome, *RUser;    sprintf(Rversion, "%s.%s", R_MAJOR, R_MINOR);    if(strcmp(getDLLVersion(), Rversion) != 0) {        fprintf(stderr, "Error: R.DLL version does not match\n");        exit(1);    }    R_setStartTime();    R_DefParamsEx(Rp, RSTART_VERSION);    if((RHome = get_R_HOME()) == NULL) {        fprintf(stderr, "R_HOME must be set in the environment or Registry\n");        exit(1);    }    Rp->rhome = RHome;    RUser = getRUser();    Rp->home = RUser;    Rp->CharacterMode = LinkDLL;    Rp->EmitEmbeddedUTF8 = FALSE;    Rp->ReadConsole = myReadConsole;    Rp->WriteConsole = myWriteConsole;    Rp->CallBack = myCallBack;    Rp->ShowMessage = askok;    Rp->YesNoCancel = askyesnocancel;    Rp->Busy = myBusy;    Rp->R_Quiet = TRUE;        /* Default is FALSE */    Rp->R_Interactive = FALSE; /* Default is TRUE */    Rp->RestoreAction = SA_RESTORE;    Rp->SaveAction = SA_NOSAVE;    R_SetParams(Rp);    freeRUser(RUser);    free_R_HOME(RHome);    R_set_command_line_arguments(argc, argv);    FlushConsoleInputBuffer(GetStdHandle(STD_INPUT_HANDLE));    signal(SIGBREAK, my_onintr);    GA_initapp(0, 0);    readconsolecfg();    setup_Rmainloop();#ifdef SIMPLE_CASE    run_Rmainloop();#else    R_ReplDLLinit();    while(R_ReplDLLdo1() > 0) {/* add user actions here if desired */    }/* only get here on EOF (not q()) */#endif    Rf_endEmbeddedR(0);    return 0;}

The ideas are

  • Check that the front-end and the linkedR.dll match – otherfront-ends may allow a looser match.
  • Find and set the R home directory and the user’s home directory. Theformer may be available from the Windows Registry: it will be inHKEY_LOCAL_MACHINE\Software\R-core\R\InstallPath from anadministrative install andHKEY_CURRENT_USER\Software\R-core\R\InstallPath otherwise, ifselected during installation (as it is by default).
  • Define startup conditions and callbacksvia theRstart structure.R_DefParams sets the defaults, andR_SetParams setsupdated values.R_DefParamsEx takes an extra argument, the versionnumber of theRstart structure provided (RSTART_VERSION refersto the current version) and returns a non-zero status when that version isnot supported by R.
  • Record the command-line arguments used byR_set_command_line_arguments for use by the R functioncommandArgs().
  • Set up the signal handler and the basic user interface.
  • Run the main R loop, possibly with our actions intermeshed.
  • Arrange to clean up.

An underlying theme is the need to keep the GUI ‘alive’, and this hasnot been done in this example. The R callbackR_ProcessEventsneeds to be called frequently to ensure that Windows events in Rwindows are handled expeditiously. Conversely, R needs to allow theGUI code (which is running in the same process) to update itself asneeded – two ways are provided to allow this:

  • R_ProcessEvents calls the callback registered byRp->callback. A version of this is used to run package Tcl/Tkfortcltk under Windows, for the code is
    void R_ProcessEvents(void){    while (peekevent()) doevent(); /* Windows events for GraphApp */    if (UserBreak) { UserBreak = FALSE; Rf_onintr(); }    R_CallBackHook();    if(R_tcldo) R_tcldo();}
  • The mainloop can be split up to allow the calling application to takesome action after each line of input has been dealt with: see thealternative code below#ifdef SIMPLE_CASE.

It may be that no R GraphApp windows need to be considered, althoughthese include pagers, thewindows() graphics device, the Rdata and script editors and various popups such aschoose.file()andselect.list(). It would be possible to replace all of these,but it seems easier to allow GraphApp to handle most of them.

It is possible to run R in a GUI in a single thread (asRGui.exe shows) but it will normally be easier180 touse multiple threads.

Note that R’s own front ends use a stack size of 10Mb, whereas MinGWexecutables default to 2Mb, and Visual C++ ones to 1Mb. The latterstack sizes are too small for a number of R applications, sogeneral-purpose front-ends should use a larger stack size.

Applications embedding R 4.2.0 and newer should useUCRT as the C runtimeand opt in for UTF-8 as the active code page in their manifest, as allfrontends shipped with R do. This will allow the embedded R to useUTF-8 as its native encoding on recent Windows systems.


Previous:, Up:Embedding R under Windows   [Contents][Index]

8.2.3 Finding R_HOME

Both applications which embed R and those which use asystemcall to invoke R (asRscript.exe,Rterm.exe orR.exe) need to be able to find the Rbin directory.The simplest way to do so is the ask the user to set an environmentvariableR_HOME and use that, but naive users may be flummoxed asto how to do so or what value to use.

The R for Windows installers have for a long time allowed the valueofR_HOME to be recorded in the Windows Registry: this isoptional but selected by default.Where it is recorded haschanged over the years to allow for multiple versions of R to beinstalled at once, and to allow 32- and 64-bit versions of R to beinstalled on the same machine. Only 64-bit versions are supported since R4.2.

The basic Registry location isSoftware\R-core\R. For anadministrative install this is underHKEY_LOCAL_MACHINE and on a64-bit OSHKEY_LOCAL_MACHINE\Software\R-core\R is by defaultredirected for a 32-bit application, so a 32-bit application will seethe information for the last 32-bit install, and a 64-bit applicationthat for the last 64-bit install. For a personal install, theinformation is underHKEY_CURRENT_USER\Software\R-core\R which isseen by both 32-bit and 64-bit applications and so records the lastinstall of either architecture. To circumvent this, with Intel builds thereare locationsSoftware\R-core\R32 andSoftware\R-core\R64which always refer to one architecture.

When R is installed and recording is not disabled then two stringvalues are written at that location for keysInstallPath andCurrent Version, and these keys are removed when R isuninstalled. To allow information about other installed versions to beretained, there is also a key named something like3.0.0 or3.0.0 patched or3.1.0 Pre-release with a value forInstallPath.

So a comprehensive algorithm to search forR_HOME is somethinglike

  • Decide which of personal or administrative installs should haveprecedence. There are arguments both ways: we find that with roamingprofiles thatHKEY_CURRENT_USER\Software often gets reverted toan earlier version. Do the following for one or both ofHKEY_CURRENT_USER andHKEY_LOCAL_MACHINE.
  • If the desired architecture is known, look inSoftware\R-core\R32orSoftware\R-core\R64, and if that does not exist or thearchitecture is immaterial, inSoftware\R-core\R.
  • If keyInstallPath exists then this isR_HOME (recordedusing backslashes). If it does not, look for version-specific keys like2.11.0 alpha, pick the latest (which is of itself a complicatedalgorithm as2.11.0 patched > 2.11.0 > 2.11.0 alpha > 2.8.1) anduse its value forInstallPath.

Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

Function and variable index

Jump to:  .  \  
A  B  C  D  E  F  G  I  L  M  N  O  P  Q  R  S  T  U  V  W  X  
Index EntrySection

.
.CInterface functions .C and .Fortran
.CallHandling R objects in C
.CallCalling .Call
.ExternalHandling R objects in C
.ExternalCalling .External
.FortranInterface functions .C and .Fortran
.Last.libLoad hooks
.onAttachLoad hooks
.onDetachLoad hooks
.onLoadLoad hooks
.onUnloadLoad hooks
.Random.seedRandom numbers

\
\abbrMarking text
\acronymMarking text
\aliasDocumenting functions
\argumentsDocumenting functions
\authorDocumenting functions
\boldMarking text
\citeMarking text
\codeMarking text
\commandMarking text
\conceptIndices
\crSectioning
\CRANpkg{pkg}User-defined macros
\deqnMathematics
\describeLists and tables
\descriptionDocumenting functions
\detailsDocumenting functions
\dfnMarking text
\doi{identifier}User-defined macros
\dontdiffDocumenting functions
\dontrunDocumenting functions
\dontshowDocumenting functions
\donttestDocumenting functions
\dotsInsertions
\dQuoteMarking text
\emailMarking text
\emphMarking text
\encInsertions
\enumerateLists and tables
\envMarking text
\eqnMathematics
\examplesDocumenting functions
\figureFigures
\fileMarking text
\formatDocumenting data sets
\hrefMarking text
\ifConditional text
\ifelseConditional text
\itemizeLists and tables
\kbdMarking text
\keywordDocumenting functions
\ldotsInsertions
\linkCross-references
\linkS4classCross-references
\methodDocumenting functions
\nameDocumenting functions
\newcommandUser-defined macros
\noteDocumenting functions
\optionMarking text
\outConditional text
\packageAuthorUser-defined macros
\packageDescriptionUser-defined macros
\packageDESCRIPTIONUser-defined macros
\packageIndicesUser-defined macros
\packageMaintainerUser-defined macros
\packageTitleUser-defined macros
\pkgMarking text
\preformattedMarking text
\RInsertions
\RdOptsDynamic pages
\referencesDocumenting functions
\renewcommandUser-defined macros
\S3methodDocumenting functions
\sampMarking text
\sectionSectioning
\seealsoDocumenting functions
\SexprDynamic pages
\sourceDocumenting data sets
\sQuoteMarking text
\sspaceUser-defined macros
\strongMarking text
\tabularLists and tables
\titleDocumenting functions
\urlMarking text
\usageDocumenting functions
\valueDocumenting functions
\varMarking text
\verbMarking text

A
addInputHandlerMeshing event loops
ALTREPWriting compact-representation-friendly code
ALTREP_CLASSWriting compact-representation-friendly code
ANY_ATTRIBNamed objects and copying
AUTHORSPackage subdirectories

B
bessel_iMathematical functions
bessel_iMathematical functions
bessel_jMathematical functions
bessel_jMathematical functions
bessel_kMathematical functions
bessel_kMathematical functions
bessel_yMathematical functions
bessel_yMathematical functions
betaMathematical functions
betaMathematical functions
BLAS_LIBSUsing Makevars
browserBrowsing

C
CAARCalling .External
CAD4RCalling .External
CAD5RCalling .External
CADDDRCalling .External
CADDRCalling .External
CADRCalling .External
CallocCharBufUser-controlled memory
CARCalling .External
CDARCalling .External
CDDDRCalling .External
CDDRCalling .External
CDRCalling .External
cgminOptimization
CHARCalculating numerical derivatives
chooseMathematical functions
chooseMathematical functions
citationPackage subdirectories
citationCITATION files
CleanEdSetting R callbacks
CLEAR_ATTRIBNamed objects and copying
COMPLEXVector accessor functions
COMPLEX_ELTVector accessor functions
COMPLEX_GET_REGIONWriting compact-representation-friendly code
COMPLEX_GET_REGIONWriting compact-representation-friendly code
COMPLEX_OR_NULLWriting compact-representation-friendly code
COMPLEX_OR_NULLWriting compact-representation-friendly code
COMPLEX_ROVector accessor functions
CONSSome convenience functions
COPYRIGHTSThe DESCRIPTION file
COPYRIGHTSPackage subdirectories
cospiNumerical Utilities
cospiNumerical Utilities

D
d1machUtility functions
DATAPTR_OR_NULLWriting compact-representation-friendly code
DATAPTR_OR_NULLWriting compact-representation-friendly code
DATAPTR_ROVector accessor functions
dbleprPrinting from Fortran
dblepr1Printing from Fortran
debugDebugging R code
debuggerDebugging R code
digammaMathematical functions
digammaMathematical functions
dpsifnMathematical functions
dpsifnMathematical functions
dump.framesDebugging R code
DUPLICATE_ATTRIBNamed objects and copying
dyn.loaddyn.load and dyn.unload
dyn.unloaddyn.load and dyn.unload

E
exp_randRandom numbers
expm1Numerical Utilities
expm1Numerical Utilities
exportSpecifying imports and exports
exportClassesNamespaces with S4 classes and methods
exportClassPatternNamespaces with S4 classes and methods
exportMethodsNamespaces with S4 classes and methods
exportPatternSpecifying imports and exports
exportPatternNamespaces with S4 classes and methods

F
FALSEMathematical constants
findIntervalUtility functions
findIntervalUtility functions
findInterval2Utility functions
findInterval2Utility functions
FLIBSUsing Makevars
fmax2Numerical Utilities
fmax2Numerical Utilities
fmin2Numerical Utilities
fmin2Numerical Utilities
fprecNumerical Utilities
fprecNumerical Utilities
fpu_setupSetting R callbacks
froundNumerical Utilities
froundNumerical Utilities
fsignNumerical Utilities
fsignNumerical Utilities
ftruncNumerical Utilities
ftruncNumerical Utilities

G
gammafnMathematical functions
gammafnMathematical functions
gctortureUsing gctorture
getInputHandlerMeshing event loops
GetRNGstateRandom numbers

I
i1machUtility functions
imax2Numerical Utilities
imax2Numerical Utilities
imin2Numerical Utilities
imin2Numerical Utilities
importSpecifying imports and exports
importClassesFromNamespaces with S4 classes and methods
importFromSpecifying imports and exports
importMethodsFromNamespaces with S4 classes and methods
INTEGERVector accessor functions
INTEGER_ELTVector accessor functions
INTEGER_GET_REGIONWriting compact-representation-friendly code
INTEGER_GET_REGIONWriting compact-representation-friendly code
INTEGER_IS_SORTEDWriting compact-representation-friendly code
INTEGER_IS_SORTEDWriting compact-representation-friendly code
INTEGER_NO_NAWriting compact-representation-friendly code
INTEGER_NO_NAWriting compact-representation-friendly code
INTEGER_OR_NULLWriting compact-representation-friendly code
INTEGER_OR_NULLWriting compact-representation-friendly code
INTEGER_ROVector accessor functions
integr_fnIntegration
intervUtility functions
intprPrinting from Fortran
intpr1Printing from Fortran
IS_LONG_VECSome convenience functions
IS_SCALARSome convenience functions
ISNAMissing and special values
ISNAMissing and IEEE values
ISNANMissing and special values
ISNANMissing and IEEE values

L
labelprPrinting from Fortran
LAPACK_LIBSUsing Makevars
lbetaMathematical functions
lbetaMathematical functions
lbfgsbOptimization
lchooseMathematical functions
lchooseMathematical functions
LCONSSome convenience functions
LCONSEvaluating R expressions from C
LENGTHCalculating numerical derivatives
lgamma1pNumerical Utilities
lgamma1pNumerical Utilities
lgammafnMathematical functions
lgammafnMathematical functions
library.dynamPackage subdirectories
library.dynamdyn.load and dyn.unload
log1mexpNumerical Utilities
log1mexpNumerical Utilities
log1pNumerical Utilities
log1pNumerical Utilities
log1pexpNumerical Utilities
log1pexpNumerical Utilities
log1pmxNumerical Utilities
log1pmxNumerical Utilities
LOGICALVector accessor functions
LOGICAL_ELTVector accessor functions
LOGICAL_GET_REGIONWriting compact-representation-friendly code
LOGICAL_GET_REGIONWriting compact-representation-friendly code
LOGICAL_NO_NAWriting compact-representation-friendly code
LOGICAL_NO_NAWriting compact-representation-friendly code
LOGICAL_OR_NULLWriting compact-representation-friendly code
LOGICAL_OR_NULLWriting compact-representation-friendly code
LOGICAL_ROVector accessor functions
logspace_addNumerical Utilities
logspace_addNumerical Utilities
logspace_subNumerical Utilities
logspace_subNumerical Utilities
logspace_sumNumerical Utilities
logspace_sumNumerical Utilities

M
M_EMathematical constants
M_PIMathematical constants
MARK_NOT_MUTABLENamed objects and copying
MAYBE_REFERENCEDNamed objects and copying
MAYBE_SHAREDNamed objects and copying
MemcpyUser-controlled memory
MemzeroUser-controlled memory

N
NA_REALMissing and IEEE values
newsPackage subdirectories
nmminOptimization
NO_REFERENCESNamed objects and copying
norm_randRandom numbers
NOT_SHAREDNamed objects and copying

O
OBJECTSUsing Makevars
OBJECTSCreating shared objects
optimfnOptimization
optimgrOptimization

P
pentagammaMathematical functions
pentagammaMathematical functions
PKG_CFLAGSCreating shared objects
PKG_CPPFLAGSCreating shared objects
PKG_CXXFLAGSCreating shared objects
PKG_FCFLAGSUsing modern Fortran code
PKG_FFLAGSCreating shared objects
PKG_LIBSCreating shared objects
PKG_OBJCFLAGSCreating shared objects
PKG_OBJCXXFLAGSCreating shared objects
pow1pNumerical Utilities
pow1pNumerical Utilities
PRINTNAMECalling .External
promptRd format
PROTECTGarbage Collection
PROTECT_WITH_INDEXGarbage Collection
psigammaMathematical functions
psigammaMathematical functions
PutRNGstateRandom numbers

Q
qsort3Utility functions
qsort3Utility functions
qsort4Utility functions
qsort4Utility functions

R
R CMD buildBuilding package tarballs
R CMD checkChecking packages
R CMD configConfigure and cleanup
R CMD Rd2pdfProcessing documentation files
R CMD RdconvProcessing documentation files
R CMD SHLIBCreating shared objects
R CMD StangleProcessing documentation files
R CMD SweaveProcessing documentation files
R_ActiveBindingFunctionSemi-internal convenience functions
R_addhistorySetting R callbacks
R_addhistorySetting R callbacks
R_allocAllocating storage
R_allocTransient storage allocation
R_allocLDTransient storage allocation
R_altrep_data1Writing compact-representation-friendly code
R_altrep_data2Writing compact-representation-friendly code
R_atofUtility functions
R_atofUtility functions
R_BindingIsActiveSemi-internal convenience functions
R_BindingIsLockedSemi-internal convenience functions
R_BusySetting R callbacks
R_BusySetting R callbacks
R_BytecodeExprWorking with closures
R_CallocUser-controlled memory
R_CHARCalculating numerical derivatives
R_check_class_etcS4 objects
R_CheckStackC stack checking
R_CheckStack2C stack checking
R_CheckUserInterruptAllowing interrupts
R_chk_callocUser-controlled memory
R_chk_freeUser-controlled memory
R_chk_reallocUser-controlled memory
R_ChooseFileSetting R callbacks
R_ChooseFileSetting R callbacks
R_CleanTempDirSetting R callbacks
R_CleanUpSetting R callbacks
R_CleanUpSetting R callbacks
R_ClearerrConsoleSetting R callbacks
R_ClearerrConsoleSetting R callbacks
R_ClearExternalPtrExternal pointers and weak references
R_ClosureBodyWorking with closures
R_ClosureEnvWorking with closures
R_ClosureExprWorking with closures
R_ClosureFormalsWorking with closures
R_compute_identicalSemi-internal convenience functions
R_ContinueUnwindCondition handling and cleanup code
R_csortUtility functions
R_csortUtility functions
R_dataentrySetting R callbacks
R_dataviewerSetting R callbacks
R_DefParamsCalling R.dll directly
R_DefParamsExCalling R.dll directly
R_DimNamesSymbolAttributes
R_do_MAKE_CLASSS4 objects
R_do_new_objectS4 objects
R_do_slotS4 objects
R_do_slot_assignS4 objects
R_dot_LastSetting R callbacks
R_EditFileSetting R callbacks
R_EditFileSetting R callbacks
R_EditFilesSetting R callbacks
R_EditFilesSetting R callbacks
R_EnvironmentIsLockedSemi-internal convenience functions
R_ExecWithCleanupCondition handling and cleanup code
R_existsVarInFrameSemi-internal convenience functions
R_ExpandFileNameUtility functions
R_ExpandFileNameUtility functions
R_ExternalPtrAddrExternal pointers and weak references
R_ExternalPtrAddrFnExternal pointers and weak references
R_ExternalPtrProtectedExternal pointers and weak references
R_ExternalPtrTagExternal pointers and weak references
R_FindNamespaceSemi-internal convenience functions
R_FindSymbolLinking to native routines in other packages
R_FINITEMissing and IEEE values
R_FlushConsoleSetting R callbacks
R_FlushConsoleSetting R callbacks
R_forceAndCallSemi-internal convenience functions
R_forceSymbolsRegistering native routines
R_FreeUser-controlled memory
R_free_tmpnamUtility functions
R_free_tmpnamUtility functions
R_GetCCallableLinking to native routines in other packages
R_getClassDefS4 objects
R_GetCurrentEnvEvaluating R expressions from C
R_GetCurrentSrcrefAccessing source references
R_getEmbeddingDllInfoRegistering symbols
R_GetSrcFilenameAccessing source references
R_getVarFinding and setting variables
R_getVarExFinding and setting variables
R_GetX11ImageOrganization of header files
R_has_slotS4 objects
R_InitFileInPStreamCustom serialization input and output
R_InitFileOutPStreamCustom serialization input and output
R_InitInPStreamCustom serialization input and output
R_InitOutPStreamCustom serialization input and output
R_INLINEInlining C functions
R_InputHandlersMeshing event loops
R_InteractiveEmbedding R under Unix-alikes
R_IsNamespaceEnvSemi-internal convenience functions
R_IsNaNMissing and IEEE values
R_isnancppMissing and special values
R_isortUtility functions
R_isortUtility functions
R_IsPackageEnvSemi-internal convenience functions
R_LIBRARY_DIRConfigure and cleanup
R_loadhistorySetting R callbacks
R_loadhistorySetting R callbacks
R_LockBindingSemi-internal convenience functions
R_LockEnvironmentSemi-internal convenience functions
R_lsInternal3Semi-internal convenience functions
R_MakeActiveBindingSemi-internal convenience functions
R_MakeExternalPtrExternal pointers and weak references
R_MakeExternalPtrFnExternal pointers and weak references
R_MakeUnwindContCondition handling and cleanup code
R_MakeWeakRefExternal pointers and weak references
R_MakeWeakRefCExternal pointers and weak references
R_max_colUtility functions
R_max_colUtility functions
R_mkClosureWorking with closures
R_NamespaceEnvSpecSemi-internal convenience functions
R_NamesSymbolAttributes
R_NegInfMissing and IEEE values
R_NewEnvFinding and setting variables
R_NewPreciousMSetGarbage Collection
R_NilValueHandling lists
R_orderVectorUtility functions
R_orderVectorUtility functions
R_orderVector1Utility functions
R_orderVector1Utility functions
R_PACKAGE_DIRConfigure and cleanup
R_PACKAGE_DIRConfigure and cleanup
R_PACKAGE_NAMEConfigure and cleanup
R_PACKAGE_NAMEConfigure and cleanup
R_PackageEnvNameSemi-internal convenience functions
R_ParentEnvSemi-internal convenience functions
R_ParseEvalStringParsing R code from C
R_ParseEvalStringParsing R code from C
R_ParseStringParsing R code from C
R_ParseStringParsing R code from C
R_ParseVectorParsing R code from C
R_PolledEventsMeshing event loops
R_PosInfMissing and IEEE values
R_powNumerical Utilities
R_powNumerical Utilities
R_pow_diNumerical Utilities
R_pow_diNumerical Utilities
R_PreserveInMSetGarbage Collection
R_PreserveObjectGarbage Collection
R_ProcessEventsCalling R.dll directly
R_ProtectWithIndexGarbage Collection
R_qsortUtility functions
R_qsortUtility functions
R_qsort_IUtility functions
R_qsort_IUtility functions
R_qsort_intUtility functions
R_qsort_intUtility functions
R_qsort_int_IUtility functions
R_qsort_int_IUtility functions
R_ReadConsoleSetting R callbacks
R_ReadConsoleSetting R callbacks
R_ReallocUser-controlled memory
R_RegisterCCallableLinking to native routines in other packages
R_RegisterCFinalizerExternal pointers and weak references
R_RegisterCFinalizerExExternal pointers and weak references
R_RegisterFinalizerExternal pointers and weak references
R_RegisterFinalizerExExternal pointers and weak references
R_registerRoutinesRegistering native routines
R_ReleaseFromMSetGarbage Collection
R_ReleaseObjectGarbage Collection
R_removeVarFromFrameSemi-internal convenience functions
R_ReplDLLdo1Embedding R under Unix-alikes
R_ReplDLLinitEmbedding R under Unix-alikes
R_ReprotectGarbage Collection
R_ResetConsoleSetting R callbacks
R_ResetConsoleSetting R callbacks
R_rsortUtility functions
R_rsortUtility functions
R_RunExitFinalizersSetting R callbacks
R_RunPendingFinalizersSetting R callbacks
R_RunWeakRefFinalizerExternal pointers and weak references
R_SaveGlobalEnvSetting R callbacks
R_savehistorySetting R callbacks
R_savehistorySetting R callbacks
R_selectlistSetting R callbacks
R_SerializeCustom serialization input and output
R_set_altrep_data1Writing compact-representation-friendly code
R_set_altrep_data2Writing compact-representation-friendly code
R_set_command_line_argumentsCalling R.dll directly
R_SetExternalPtrAddrExternal pointers and weak references
R_SetExternalPtrProtectedExternal pointers and weak references
R_SetExternalPtrTagExternal pointers and weak references
R_SetParamsCalling R.dll directly
R_setStartTimeCalling R.dll directly
R_ShowFilesSetting R callbacks
R_ShowFilesSetting R callbacks
R_ShowMessageSetting R callbacks
R_ShowMessageSetting R callbacks
R_SrcrefAccessing source references
R_strtodUtility functions
R_strtodUtility functions
R_SuicideSetting R callbacks
R_TempDirEmbedding R under Unix-alikes
R_tmpnamUtility functions
R_tmpnamUtility functions
R_tmpnam2Utility functions
R_tmpnam2Utility functions
R_ToplevelExecCondition handling and cleanup code
R_tryCatchCondition handling and cleanup code
R_tryCatchErrorCondition handling and cleanup code
R_tryEvalCondition handling and cleanup code
R_tryEvalSilentCondition handling and cleanup code
R_unif_indexRandom numbers
R_unLockBindingSemi-internal convenience functions
R_UnserializeCustom serialization input and output
R_UnwindProtectCondition handling and cleanup code
R_useDynamicSymbolsRegistering native routines
R_VersionPlatform and version information
R_wait_usecMeshing event loops
R_WeakRefKeyExternal pointers and weak references
R_WeakRefValueExternal pointers and weak references
R_withCallingErrorHandlerCondition handling and cleanup code
R_WriteConsoleSetting R callbacks
R_WriteConsoleSetting R callbacks
R_WriteConsoleExSetting R callbacks
R_WriteConsoleExSetting R callbacks
RAWVector accessor functions
RAW_ELTVector accessor functions
RAW_GET_REGIONWriting compact-representation-friendly code
RAW_GET_REGIONWriting compact-representation-friendly code
RAW_OR_NULLWriting compact-representation-friendly code
RAW_OR_NULLWriting compact-representation-friendly code
RAW_ROVector accessor functions
rchkusrAllowing interrupts
RdqagiIntegration
RdqagsIntegration
REALVector accessor functions
REAL_ELTVector accessor functions
REAL_GET_REGIONWriting compact-representation-friendly code
REAL_GET_REGIONWriting compact-representation-friendly code
REAL_IS_SORTEDWriting compact-representation-friendly code
REAL_IS_SORTEDWriting compact-representation-friendly code
REAL_NO_NAWriting compact-representation-friendly code
REAL_NO_NAWriting compact-representation-friendly code
REAL_OR_NULLWriting compact-representation-friendly code
REAL_OR_NULLWriting compact-representation-friendly code
REAL_ROVector accessor functions
realprPrinting from Fortran
realpr1Printing from Fortran
recoverDebugging R code
removeInputHandlerMeshing event loops
REprintfPrinting
REPROTECTGarbage Collection
REvprintfPrinting
rexitError signaling from Fortran
Rf_alloc3DArrayAllocating storage
Rf_allocArrayAllocating storage
Rf_allocLangEvaluating R expressions from C
Rf_allocListHandling lists
Rf_allocListEvaluating R expressions from C
Rf_allocMatrixAllocating storage
Rf_allocMatrixCalculating numerical derivatives
Rf_allocS4ObjectS4 objects
Rf_allocVectorAllocating storage
Rf_any_duplicatedSemi-internal convenience functions
Rf_any_duplicated3Semi-internal convenience functions
Rf_asBboolSome convenience functions
Rf_asCharSome convenience functions
Rf_asCharacterFactorSome convenience functions
Rf_asComplexSome convenience functions
Rf_asIntegerSome convenience functions
Rf_asLogicalSome convenience functions
Rf_asRbooleanSome convenience functions
Rf_asRealSome convenience functions
Rf_asS4S4 objects
Rf_charIsASCIICharacter encoding issues
Rf_charIsLatin1Character encoding issues
Rf_charIsUTF8Character encoding issues
Rf_classgetsClasses
Rf_coerceVectorDetails of R types
Rf_consSome convenience functions
Rf_copyListMatrixSemi-internal convenience functions
Rf_copyMatrixAllocating storage
Rf_copyMostAttribAllocating storage
Rf_copyVectorAllocating storage
Rf_cPsortUtility functions
Rf_cPsortUtility functions
Rf_defineVarFinding and setting variables
Rf_dimgetsAttributes
Rf_dimnamesgetsAttributes
Rf_duplicateNamed objects and copying
Rf_duplicatedSemi-internal convenience functions
Rf_eltSome convenience functions
Rf_endEmbeddedREmbedding R under Unix-alikes
Rf_errorError signaling
Rf_errorcallError signaling
Rf_evalEvaluating R expressions from C
Rf_findFunEvaluating R expressions from C
Rf_GetArrayDimnamesAttributes
Rf_getAttribAttributes
Rf_getCharCECharacter encoding issues
Rf_GetColNamesAttributes
Rf_GetMatrixDimnamesAttributes
Rf_GetOption1Semi-internal convenience functions
Rf_GetOptionWidthSemi-internal convenience functions
Rf_GetRowNamesAttributes
Rf_inheritsSemi-internal convenience functions
Rf_initEmbeddedREmbedding R under Unix-alikes
Rf_initialize_REmbedding R under Unix-alikes
Rf_installAttributes
Rf_installCharAttributes
Rf_installCharFinding and setting variables
Rf_installTrCharAttributes
Rf_iPsortUtility functions
Rf_iPsortUtility functions
Rf_isArraySome convenience functions
Rf_isBlankStringSome convenience functions
Rf_isComplexDetails of R types
Rf_isDataFrameSome convenience functions
Rf_isEnvironmentDetails of R types
Rf_isExpressionDetails of R types
Rf_isFactorSome convenience functions
Rf_isFunctionSome convenience functions
Rf_isIntegerDetails of R types
Rf_isLanguageSome convenience functions
Rf_isListSome convenience functions
Rf_isLogicalDetails of R types
Rf_isMatrixSome convenience functions
Rf_isNewListSome convenience functions
Rf_isNullDetails of R types
Rf_isNumberSome convenience functions
Rf_isNumericSome convenience functions
Rf_isObjectSome convenience functions
Rf_isOrderedSome convenience functions
Rf_isPairListSome convenience functions
Rf_isPrimitiveSome convenience functions
Rf_isRealDetails of R types
Rf_isS4Some convenience functions
Rf_isStringDetails of R types
Rf_isSymbolDetails of R types
Rf_isTsSome convenience functions
Rf_isUnorderedSome convenience functions
Rf_isUnsortedSemi-internal convenience functions
Rf_isVectorSome convenience functions
Rf_isVectorAtomicSome convenience functions
Rf_isVectorizableSemi-internal convenience functions
Rf_isVectorListSome convenience functions
Rf_KillAllDevicesSetting R callbacks
Rf_lang1Some convenience functions
Rf_lang2Some convenience functions
Rf_lang3Some convenience functions
Rf_lang4Some convenience functions
Rf_lang5Some convenience functions
Rf_lang6Some convenience functions
Rf_lastEltSome convenience functions
Rf_lconsSome convenience functions
Rf_lengthCalculating numerical derivatives
Rf_lengthgetsAllocating storage
Rf_list1Some convenience functions
Rf_list2Some convenience functions
Rf_list3Some convenience functions
Rf_list4Some convenience functions
Rf_list5Some convenience functions
Rf_list6Some convenience functions
Rf_listAppendSemi-internal convenience functions
Rf_mainloopEmbedding R under Unix-alikes
Rf_matchSemi-internal convenience functions
Rf_mkCharHandling character data
Rf_mkCharCECharacter encoding issues
Rf_mkCharLenHandling character data
Rf_mkCharLenCECharacter encoding issues
Rf_mkNamedAttributes
Rf_mkStringSome convenience functions
Rf_namesgetsAttributes
Rf_ncolsTransient storage allocation
Rf_nlevelsSemi-internal convenience functions
Rf_nrowsTransient storage allocation
Rf_nthcdrSome convenience functions
Rf_onintrCalling R.dll directly
Rf_PairToVectorListSemi-internal convenience functions
Rf_pmatchSemi-internal convenience functions
Rf_PrintValueInspecting R objects
Rf_protectGarbage Collection
Rf_psmatchSemi-internal convenience functions
Rf_reEncCharacter encoding issues
Rf_revsortUtility functions
Rf_revsortUtility functions
Rf_rPsortUtility functions
Rf_rPsortUtility functions
Rf_ScalarComplexSome convenience functions
Rf_ScalarIntegerSome convenience functions
Rf_ScalarLogicalSome convenience functions
Rf_ScalarRawSome convenience functions
Rf_ScalarRealSome convenience functions
Rf_ScalarStringSome convenience functions
Rf_setAttribAttributes
Rf_setVarFinding and setting variables
Rf_shallow_duplicateNamed objects and copying
Rf_str2typeSome convenience functions
Rf_StringBlankSome convenience functions
Rf_StringFalseSome convenience functions
Rf_StringTrueSome convenience functions
Rf_topenvSemi-internal convenience functions
Rf_translateCharCharacter encoding issues
Rf_translateCharUTF8Character encoding issues
Rf_type2charSome convenience functions
Rf_type2strSome convenience functions
Rf_type2str_nowarnSome convenience functions
Rf_unprotectGarbage Collection
Rf_unprotect_ptrGarbage Collection
Rf_VectorToPairListSemi-internal convenience functions
Rf_warningError signaling
Rf_warningcallError signaling
Rf_warningcall_immediateError signaling
Rf_xlengthPortable C and C++ code
Rf_xlengthgetsAllocating storage
RiconvRe-encoding
RiconvRe-encoding
Riconv_closeRe-encoding
Riconv_closeRe-encoding
Riconv_openRe-encoding
Riconv_openRe-encoding
rmultinomDistribution functions
RprintfPrinting
RprofProfiling R code for speed
RprofMemory statistics from Rprof
RprofmemTracking memory allocations
rsort_with_indexUtility functions
rsort_with_indexUtility functions
RtanpiNumerical Utilities
RtanpiNumerical Utilities
run_RmainloopEmbedding R under Unix-alikes
RvprintfPrinting
rwarnError signaling from Fortran

S
S_allocTransient storage allocation
S_reallocTransient storage allocation
S3methodRegistering S3 methods
SAFE_FFLAGSUsing Makevars
saminOptimization
SET_COMPLEX_ELTVector accessor functions
SET_INTEGER_ELTVector accessor functions
SET_LOGICAL_ELTVector accessor functions
SET_RAW_ELTVector accessor functions
SET_REAL_ELTVector accessor functions
SET_STRING_ELTHandling character data
SET_TAGEvaluating R expressions from C
SET_VECTOR_ELTVector accessor functions
SETCAD4RCalling .External
SETCADDDRCalling .External
SETCADDRCalling .External
SETCADRCalling .External
SETCARCalling .External
SETCDRCalling .External
setup_RmainloopCalling R.dll directly
SHALLOW_DUPLICATE_ATTRIBNamed objects and copying
signNumerical Utilities
signNumerical Utilities
signrank_freeDistribution functions
sinpiNumerical Utilities
sinpiNumerical Utilities
STRING_ELTHandling character data
STRING_IS_SORTEDWriting compact-representation-friendly code
STRING_IS_SORTEDWriting compact-representation-friendly code
STRING_NO_NAWriting compact-representation-friendly code
STRING_NO_NAWriting compact-representation-friendly code
STRING_PTR_ROVector accessor functions
summaryRprofMemory statistics from Rprof
systemOperating system access
system.timeOperating system access
system2Operating system access

T
TAGCalling .External
tanpiNumerical Utilities
tanpiNumerical Utilities
tetragammaMathematical functions
tetragammaMathematical functions
traceDebugging R code
tracebackDebugging R code
tracememTracing copies of an object
trigammaMathematical functions
trigammaMathematical functions
TRUEMathematical constants
TYPEOFCalling .External

U
undebugDebugging R code
unif_randRandom numbers
UNPROTECTGarbage Collection
UNPROTECT_PTRGarbage Collection
untracememTracing copies of an object
useDynLibuseDynLib

V
VECTOR_ELTVector accessor functions
VECTOR_PTR_ROVector accessor functions
vmaxgetTransient storage allocation
vmaxsetTransient storage allocation
vmminOptimization

W
wilcox_freeDistribution functions

X
XLENGTHPortable C and C++ code

Jump to:  .  \  
A  B  C  D  E  F  G  I  L  M  N  O  P  Q  R  S  T  U  V  W  X  

Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

API index

Entry points and variables listed in this index and in header fileslisted here are intended to be used in distributed packages and ideallywill only be changed after deprecation.

Jump to:  A  B  C  D  E  F  G  I  L  M  N  O  P  R  S  T  U  V  W  X  
Index EntrySection

A
ANY_ATTRIBNamed objects and copying

B
bessel_iMathematical functions
bessel_jMathematical functions
bessel_kMathematical functions
bessel_yMathematical functions
betaMathematical functions

C
CAARCalling .External
CAD4RCalling .External
CAD5RCalling .External
CADDDRCalling .External
CADDRCalling .External
CADRCalling .External
CARCalling .External
CDARCalling .External
CDDDRCalling .External
CDDRCalling .External
CDRCalling .External
cgminOptimization
CHARCalculating numerical derivatives
chooseMathematical functions
CLEAR_ATTRIBNamed objects and copying
COMPLEXVector accessor functions
COMPLEX_ELTVector accessor functions
COMPLEX_ROVector accessor functions
CONSSome convenience functions
cospiNumerical Utilities

D
d1machUtility functions
DATAPTR_ROVector accessor functions
digammaMathematical functions
dpsifnMathematical functions
DUPLICATE_ATTRIBNamed objects and copying

E
exp_randRandom numbers
expm1Numerical Utilities

F
FALSEMathematical constants
findIntervalUtility functions
findInterval2Utility functions
fmax2Numerical Utilities
fmin2Numerical Utilities
fprecNumerical Utilities
froundNumerical Utilities
fsignNumerical Utilities
ftruncNumerical Utilities

G
gammafnMathematical functions
GetRNGstateRandom numbers

I
i1machUtility functions
imax2Numerical Utilities
imin2Numerical Utilities
INTEGERVector accessor functions
INTEGER_ELTVector accessor functions
INTEGER_ROVector accessor functions
integr_fnIntegration
intervUtility functions
ISNAMissing and special values
ISNAMissing and IEEE values
ISNANMissing and special values
ISNANMissing and IEEE values

L
lbetaMathematical functions
lbfgsbOptimization
lchooseMathematical functions
LCONSSome convenience functions
LCONSEvaluating R expressions from C
LENGTHCalculating numerical derivatives
lgamma1pNumerical Utilities
lgammafnMathematical functions
log1mexpNumerical Utilities
log1pNumerical Utilities
log1pexpNumerical Utilities
log1pmxNumerical Utilities
LOGICALVector accessor functions
LOGICAL_ELTVector accessor functions
LOGICAL_ROVector accessor functions
logspace_addNumerical Utilities
logspace_subNumerical Utilities
logspace_sumNumerical Utilities

M
M_EMathematical constants
M_PIMathematical constants
MARK_NOT_MUTABLENamed objects and copying
MAYBE_REFERENCEDNamed objects and copying
MAYBE_SHAREDNamed objects and copying

N
NA_REALMissing and IEEE values
nmminOptimization
NO_REFERENCESNamed objects and copying
norm_randRandom numbers
NOT_SHAREDNamed objects and copying

O
optimfnOptimization
optimgrOptimization

P
pentagammaMathematical functions
pow1pNumerical Utilities
PRINTNAMECalling .External
PROTECTGarbage Collection
PROTECT_WITH_INDEXGarbage Collection
psigammaMathematical functions
PutRNGstateRandom numbers

R
R_allocAllocating storage
R_allocTransient storage allocation
R_allocLDTransient storage allocation
R_atofUtility functions
R_BytecodeExprWorking with closures
R_CallocUser-controlled memory
R_CHARCalculating numerical derivatives
R_CheckStackC stack checking
R_CheckStack2C stack checking
R_CheckUserInterruptAllowing interrupts
R_ClearExternalPtrExternal pointers and weak references
R_ClosureBodyWorking with closures
R_ClosureEnvWorking with closures
R_ClosureExprWorking with closures
R_ClosureFormalsWorking with closures
R_ContinueUnwindCondition handling and cleanup code
R_csortUtility functions
R_DimNamesSymbolAttributes
R_ExecWithCleanupCondition handling and cleanup code
R_ExpandFileNameUtility functions
R_ext/Arith.hMissing and special values
R_ext/BLAS.hNumerical analysis subroutines
R_ext/Boolean.hMathematical constants
R_ext/Complex.hInterface functions .C and .Fortran
R_ext/Constants.hMathematical constants
R_ext/Error.hThe R API
R_ext/Lapack.hNumerical analysis subroutines
R_ext/Linpack.hNumerical analysis subroutines
R_ext/Memory.hOrganization of header files
R_ext/Random.hOrganization of header files
R_ext/Riconv.hRe-encoding
R_ext/Visibility.hConverting a package to use registration
R_ExternalPtrAddrExternal pointers and weak references
R_ExternalPtrAddrFnExternal pointers and weak references
R_ExternalPtrProtectedExternal pointers and weak references
R_ExternalPtrTagExternal pointers and weak references
R_FindSymbolLinking to native routines in other packages
R_FINITEMissing and IEEE values
R_forceSymbolsRegistering native routines
R_FreeUser-controlled memory
R_free_tmpnamUtility functions
R_GetCCallableLinking to native routines in other packages
R_GetCurrentSrcrefAccessing source references
R_GetSrcFilenameAccessing source references
R_getVarFinding and setting variables
R_getVarExFinding and setting variables
R_INLINEInlining C functions
R_IsNaNMissing and IEEE values
R_isnancppMissing and special values
R_isortUtility functions
R_MakeExternalPtrExternal pointers and weak references
R_MakeExternalPtrFnExternal pointers and weak references
R_MakeUnwindContCondition handling and cleanup code
R_MakeWeakRefExternal pointers and weak references
R_MakeWeakRefCExternal pointers and weak references
R_max_colUtility functions
R_mkClosureWorking with closures
R_NamesSymbolAttributes
R_NegInfMissing and IEEE values
R_NewEnvFinding and setting variables
R_NewPreciousMSetGarbage Collection
R_NilValueHandling lists
R_orderVectorUtility functions
R_orderVector1Utility functions
R_ParentEnvSemi-internal convenience functions
R_ParseEvalStringParsing R code from C
R_ParseStringParsing R code from C
R_ParseVectorParsing R code from C
R_PosInfMissing and IEEE values
R_powNumerical Utilities
R_pow_diNumerical Utilities
R_PreserveInMSetGarbage Collection
R_PreserveObjectGarbage Collection
R_ProtectWithIndexGarbage Collection
R_qsortUtility functions
R_qsort_IUtility functions
R_qsort_intUtility functions
R_qsort_int_IUtility functions
R_ReallocUser-controlled memory
R_RegisterCCallableLinking to native routines in other packages
R_RegisterCFinalizerExternal pointers and weak references
R_RegisterCFinalizerExExternal pointers and weak references
R_RegisterFinalizerExternal pointers and weak references
R_RegisterFinalizerExExternal pointers and weak references
R_registerRoutinesRegistering native routines
R_ReleaseFromMSetGarbage Collection
R_ReleaseObjectGarbage Collection
R_ReprotectGarbage Collection
R_rsortUtility functions
R_RunWeakRefFinalizerExternal pointers and weak references
R_SetExternalPtrAddrExternal pointers and weak references
R_SetExternalPtrProtectedExternal pointers and weak references
R_SetExternalPtrTagExternal pointers and weak references
R_ShowMessageSetting R callbacks
R_strtodUtility functions
R_tmpnamUtility functions
R_tmpnam2Utility functions
R_ToplevelExecCondition handling and cleanup code
R_tryCatchCondition handling and cleanup code
R_tryCatchErrorCondition handling and cleanup code
R_tryEvalCondition handling and cleanup code
R_tryEvalSilentCondition handling and cleanup code
R_unif_indexRandom numbers
R_UnwindProtectCondition handling and cleanup code
R_useDynamicSymbolsRegistering native routines
R_VersionPlatform and version information
R_WeakRefKeyExternal pointers and weak references
R_WeakRefValueExternal pointers and weak references
R_withCallingErrorHandlerCondition handling and cleanup code
RAWVector accessor functions
RAW_ELTVector accessor functions
RAW_ROVector accessor functions
RdqagiIntegration
RdqagsIntegration
REALVector accessor functions
REAL_ELTVector accessor functions
REAL_ROVector accessor functions
REprintfPrinting
REPROTECTGarbage Collection
REvprintfPrinting
Rf_alloc3DArrayAllocating storage
Rf_allocArrayAllocating storage
Rf_allocLangEvaluating R expressions from C
Rf_allocListHandling lists
Rf_allocListEvaluating R expressions from C
Rf_allocMatrixAllocating storage
Rf_allocMatrixCalculating numerical derivatives
Rf_allocVectorAllocating storage
Rf_asBboolSome convenience functions
Rf_asCharSome convenience functions
Rf_asCharacterFactorSome convenience functions
Rf_asComplexSome convenience functions
Rf_asIntegerSome convenience functions
Rf_asLogicalSome convenience functions
Rf_asRbooleanSome convenience functions
Rf_asRealSome convenience functions
Rf_classgetsClasses
Rf_coerceVectorDetails of R types
Rf_consSome convenience functions
Rf_copyMatrixAllocating storage
Rf_copyMostAttribAllocating storage
Rf_copyVectorAllocating storage
Rf_cPsortUtility functions
Rf_defineVarFinding and setting variables
Rf_dimgetsAttributes
Rf_dimnamesgetsAttributes
Rf_duplicateNamed objects and copying
Rf_eltSome convenience functions
Rf_errorError signaling
Rf_errorcallError signaling
Rf_evalEvaluating R expressions from C
Rf_findFunEvaluating R expressions from C
Rf_GetArrayDimnamesAttributes
Rf_getAttribAttributes
Rf_getCharCECharacter encoding issues
Rf_GetColNamesAttributes
Rf_GetMatrixDimnamesAttributes
Rf_GetOption1Semi-internal convenience functions
Rf_GetOptionWidthSemi-internal convenience functions
Rf_GetRowNamesAttributes
Rf_inheritsSemi-internal convenience functions
Rf_installAttributes
Rf_installCharAttributes
Rf_installCharFinding and setting variables
Rf_installTrCharAttributes
Rf_iPsortUtility functions
Rf_isArraySome convenience functions
Rf_isComplexDetails of R types
Rf_isDataFrameSome convenience functions
Rf_isEnvironmentDetails of R types
Rf_isExpressionDetails of R types
Rf_isFactorSome convenience functions
Rf_isFunctionSome convenience functions
Rf_isIntegerDetails of R types
Rf_isLanguageSome convenience functions
Rf_isListSome convenience functions
Rf_isLogicalDetails of R types
Rf_isMatrixSome convenience functions
Rf_isNewListSome convenience functions
Rf_isNullDetails of R types
Rf_isNumberSome convenience functions
Rf_isNumericSome convenience functions
Rf_isObjectSome convenience functions
Rf_isOrderedSome convenience functions
Rf_isPairListSome convenience functions
Rf_isPrimitiveSome convenience functions
Rf_isRealDetails of R types
Rf_isS4Some convenience functions
Rf_isStringDetails of R types
Rf_isSymbolDetails of R types
Rf_isTsSome convenience functions
Rf_isUnorderedSome convenience functions
Rf_isVectorSome convenience functions
Rf_isVectorAtomicSome convenience functions
Rf_isVectorListSome convenience functions
Rf_lang1Some convenience functions
Rf_lang2Some convenience functions
Rf_lang3Some convenience functions
Rf_lang4Some convenience functions
Rf_lang5Some convenience functions
Rf_lang6Some convenience functions
Rf_lastEltSome convenience functions
Rf_lconsSome convenience functions
Rf_lengthCalculating numerical derivatives
Rf_lengthgetsAllocating storage
Rf_list1Some convenience functions
Rf_list2Some convenience functions
Rf_list3Some convenience functions
Rf_list4Some convenience functions
Rf_list5Some convenience functions
Rf_list6Some convenience functions
Rf_mkCharHandling character data
Rf_mkCharCECharacter encoding issues
Rf_mkCharLenHandling character data
Rf_mkCharLenCECharacter encoding issues
Rf_mkNamedAttributes
Rf_mkStringSome convenience functions
Rf_namesgetsAttributes
Rf_ncolsTransient storage allocation
Rf_nrowsTransient storage allocation
Rf_nthcdrSome convenience functions
Rf_onintrCalling R.dll directly
Rf_PrintValueInspecting R objects
Rf_protectGarbage Collection
Rf_reEncCharacter encoding issues
Rf_revsortUtility functions
Rf_rPsortUtility functions
Rf_ScalarComplexSome convenience functions
Rf_ScalarIntegerSome convenience functions
Rf_ScalarLogicalSome convenience functions
Rf_ScalarRawSome convenience functions
Rf_ScalarRealSome convenience functions
Rf_ScalarStringSome convenience functions
Rf_setAttribAttributes
Rf_setVarFinding and setting variables
Rf_shallow_duplicateNamed objects and copying
Rf_str2typeSome convenience functions
Rf_topenvSemi-internal convenience functions
Rf_translateCharCharacter encoding issues
Rf_translateCharUTF8Character encoding issues
Rf_type2charSome convenience functions
Rf_type2strSome convenience functions
Rf_type2str_nowarnSome convenience functions
Rf_unprotectGarbage Collection
Rf_unprotect_ptrGarbage Collection
Rf_warningError signaling
Rf_warningcallError signaling
Rf_warningcall_immediateError signaling
Rf_xlengthPortable C and C++ code
Rf_xlengthgetsAllocating storage
RiconvRe-encoding
Riconv_closeRe-encoding
Riconv_openRe-encoding
Rmath.hNumerical analysis subroutines
rmultinomDistribution functions
RprintfPrinting
rsort_with_indexUtility functions
RtanpiNumerical Utilities
RvprintfPrinting

S
S_allocTransient storage allocation
S_reallocTransient storage allocation
saminOptimization
SET_COMPLEX_ELTVector accessor functions
SET_INTEGER_ELTVector accessor functions
SET_LOGICAL_ELTVector accessor functions
SET_RAW_ELTVector accessor functions
SET_REAL_ELTVector accessor functions
SET_STRING_ELTHandling character data
SET_TAGEvaluating R expressions from C
SET_VECTOR_ELTVector accessor functions
SETCAD4RCalling .External
SETCADDDRCalling .External
SETCADDRCalling .External
SETCADRCalling .External
SETCARCalling .External
SETCDRCalling .External
SHALLOW_DUPLICATE_ATTRIBNamed objects and copying
signNumerical Utilities
signrank_freeDistribution functions
sinpiNumerical Utilities
STRING_ELTHandling character data
STRING_PTR_ROVector accessor functions

T
TAGCalling .External
tanpiNumerical Utilities
tetragammaMathematical functions
trigammaMathematical functions
TRUEMathematical constants
TYPEOFCalling .External

U
unif_randRandom numbers
UNPROTECTGarbage Collection
UNPROTECT_PTRGarbage Collection

V
VECTOR_ELTVector accessor functions
VECTOR_PTR_ROVector accessor functions
vmaxgetTransient storage allocation
vmaxsetTransient storage allocation
vmminOptimization

W
wilcox_freeDistribution functions

X
XLENGTHPortable C and C++ code

Jump to:  A  B  C  D  E  F  G  I  L  M  N  O  P  R  S  T  U  V  W  X  

Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

Fortran API index

Entry points listed in this index are intended to be usedfromFortran code in distributed packages and ideally will only be changedafter deprecation.

Jump to:  D  I  L  Q  R  
Index EntrySection

D
dbleprPrinting from Fortran
dblepr1Printing from Fortran

I
intprPrinting from Fortran
intpr1Printing from Fortran

L
labelprPrinting from Fortran

Q
qsort3Utility functions
qsort4Utility functions

R
rchkusrAllowing interrupts
realprPrinting from Fortran
realpr1Printing from Fortran
rexitError signaling from Fortran
rwarnError signaling from Fortran

Jump to:  D  I  L  Q  R  

Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

Experimental API index

Entry points and variables listed in this index and in header fileslisted here are part of an experimental API, such asR_ext/Altrep.h. These are subject to change, so package authors wishingto use these should be prepared to adapt.

Jump to:  A  C  D  I  L  R  S  
Index EntrySection

A
ALTREPWriting compact-representation-friendly code
ALTREP_CLASSWriting compact-representation-friendly code

C
COMPLEX_GET_REGIONWriting compact-representation-friendly code
COMPLEX_OR_NULLWriting compact-representation-friendly code

D
DATAPTR_OR_NULLWriting compact-representation-friendly code

I
INTEGER_GET_REGIONWriting compact-representation-friendly code
INTEGER_IS_SORTEDWriting compact-representation-friendly code
INTEGER_NO_NAWriting compact-representation-friendly code
INTEGER_OR_NULLWriting compact-representation-friendly code
IS_LONG_VECSome convenience functions
IS_SCALARSome convenience functions

L
LOGICAL_GET_REGIONWriting compact-representation-friendly code
LOGICAL_NO_NAWriting compact-representation-friendly code
LOGICAL_OR_NULLWriting compact-representation-friendly code

R
R_ActiveBindingFunctionSemi-internal convenience functions
R_altrep_data1Writing compact-representation-friendly code
R_altrep_data2Writing compact-representation-friendly code
R_BindingIsActiveSemi-internal convenience functions
R_BindingIsLockedSemi-internal convenience functions
R_check_class_etcS4 objects
R_chk_callocUser-controlled memory
R_chk_freeUser-controlled memory
R_chk_reallocUser-controlled memory
R_compute_identicalSemi-internal convenience functions
R_do_MAKE_CLASSS4 objects
R_do_new_objectS4 objects
R_do_slotS4 objects
R_do_slot_assignS4 objects
R_EnvironmentIsLockedSemi-internal convenience functions
R_existsVarInFrameSemi-internal convenience functions
R_ext/Altrep.hWriting compact-representation-friendly code
R_ext/Altrep.hThe R API
R_ext/GraphicsDevice.hOrganization of header files
R_ext/GraphicsEngine.hOrganization of header files
R_ext/QuartzDevice.hOrganization of header files
R_FindNamespaceSemi-internal convenience functions
R_forceAndCallSemi-internal convenience functions
R_getClassDefS4 objects
R_GetX11ImageOrganization of header files
R_has_slotS4 objects
R_InitFileInPStreamCustom serialization input and output
R_InitFileOutPStreamCustom serialization input and output
R_InitInPStreamCustom serialization input and output
R_InitOutPStreamCustom serialization input and output
R_IsNamespaceEnvSemi-internal convenience functions
R_IsPackageEnvSemi-internal convenience functions
R_LockBindingSemi-internal convenience functions
R_LockEnvironmentSemi-internal convenience functions
R_lsInternal3Semi-internal convenience functions
R_MakeActiveBindingSemi-internal convenience functions
R_NamespaceEnvSpecSemi-internal convenience functions
R_PackageEnvNameSemi-internal convenience functions
R_removeVarFromFrameSemi-internal convenience functions
R_SerializeCustom serialization input and output
R_set_altrep_data1Writing compact-representation-friendly code
R_set_altrep_data2Writing compact-representation-friendly code
R_unLockBindingSemi-internal convenience functions
R_UnserializeCustom serialization input and output
RAW_GET_REGIONWriting compact-representation-friendly code
RAW_OR_NULLWriting compact-representation-friendly code
REAL_GET_REGIONWriting compact-representation-friendly code
REAL_IS_SORTEDWriting compact-representation-friendly code
REAL_NO_NAWriting compact-representation-friendly code
REAL_OR_NULLWriting compact-representation-friendly code
Rf_allocS4ObjectS4 objects
Rf_any_duplicatedSemi-internal convenience functions
Rf_any_duplicated3Semi-internal convenience functions
Rf_asS4S4 objects
Rf_charIsASCIICharacter encoding issues
Rf_charIsLatin1Character encoding issues
Rf_charIsUTF8Character encoding issues
Rf_copyListMatrixSemi-internal convenience functions
Rf_duplicatedSemi-internal convenience functions
Rf_isBlankStringSome convenience functions
Rf_isUnsortedSemi-internal convenience functions
Rf_isVectorizableSemi-internal convenience functions
Rf_listAppendSemi-internal convenience functions
Rf_matchSemi-internal convenience functions
Rf_nlevelsSemi-internal convenience functions
Rf_PairToVectorListSemi-internal convenience functions
Rf_pmatchSemi-internal convenience functions
Rf_psmatchSemi-internal convenience functions
Rf_StringBlankSome convenience functions
Rf_StringFalseSome convenience functions
Rf_StringTrueSome convenience functions
Rf_VectorToPairListSemi-internal convenience functions

S
STRING_IS_SORTEDWriting compact-representation-friendly code
STRING_NO_NAWriting compact-representation-friendly code

Jump to:  A  C  D  I  L  R  S  

Next:, Previous:, Up:Writing R Extensions   [Contents][Index]

Embedding API index

Functions, variables, and header files to support creating alternatefront ends and other forms of embedding R.

Jump to:  A  C  F  G  R  S  
Index EntrySection

A
addInputHandlerMeshing event loops

C
CleanEdSetting R callbacks

F
fpu_setupSetting R callbacks

G
getInputHandlerMeshing event loops

R
R_addhistorySetting R callbacks
R_BusySetting R callbacks
R_ChooseFileSetting R callbacks
R_CleanTempDirSetting R callbacks
R_CleanUpSetting R callbacks
R_ClearerrConsoleSetting R callbacks
R_DefParamsCalling R.dll directly
R_DefParamsExCalling R.dll directly
R_dot_LastSetting R callbacks
R_EditFileSetting R callbacks
R_EditFilesSetting R callbacks
R_ext/RStartup.hCalling R.dll directly
R_FlushConsoleSetting R callbacks
R_getEmbeddingDllInfoRegistering symbols
R_InputHandlersMeshing event loops
R_InteractiveEmbedding R under Unix-alikes
R_loadhistorySetting R callbacks
R_PolledEventsMeshing event loops
R_ProcessEventsCalling R.dll directly
R_ReadConsoleSetting R callbacks
R_ReplDLLdo1Embedding R under Unix-alikes
R_ReplDLLinitEmbedding R under Unix-alikes
R_ResetConsoleSetting R callbacks
R_RunExitFinalizersSetting R callbacks
R_RunPendingFinalizersSetting R callbacks
R_SaveGlobalEnvSetting R callbacks
R_savehistorySetting R callbacks
R_set_command_line_argumentsCalling R.dll directly
R_SetParamsCalling R.dll directly
R_setStartTimeCalling R.dll directly
R_ShowFilesSetting R callbacks
R_TempDirEmbedding R under Unix-alikes
R_wait_usecMeshing event loops
R_WriteConsoleSetting R callbacks
R_WriteConsoleExSetting R callbacks
Rembedded.hEmbedding R under Unix-alikes
removeInputHandlerMeshing event loops
Rf_endEmbeddedREmbedding R under Unix-alikes
Rf_initEmbeddedREmbedding R under Unix-alikes
Rf_KillAllDevicesSetting R callbacks
Rinterface.hEmbedding R under Unix-alikes
run_RmainloopEmbedding R under Unix-alikes

S
setup_RmainloopCalling R.dll directly

Jump to:  A  C  F  G  R  S  

Previous:, Up:Writing R Extensions   [Contents][Index]

Concept index

Jump to:  .  
A  B  C  D  E  F  G  H  I  L  M  N  O  P  R  S  T  U  V  W  Z  
Index EntrySection

.
.install_extras fileWriting package vignettes
.Rbuildignore fileBuilding package tarballs
.Rinstignore filePackage subdirectories

A
Allocating storageAllocating storage
AttributesAttributes

B
Bessel functionsMathematical functions
Beta functionMathematical functions
Building binary packagesBuilding binary packages
Building source packagesBuilding package tarballs

C
C stack checkingC stack checking
C++ code, interfacingInterfacing C++ code
Calling C from Fortran and vice versaCalling C from Fortran and vice versa
Checking packagesChecking packages
CITATION filePackage subdirectories
CITATION fileCITATION files
ClassesClasses
Cleanup codeCondition handling and cleanup code
cleanup filePackage structure
Condition handlingCondition handling and cleanup code
conditionalsConditional text
configure filePackage structure
Copying objectsNamed objects and copying
CRANCreating R packages
Creating packagesCreating R packages
Creating shared objectsCreating shared objects
Cross-references in documentationCross-references
cumulative hazardDistribution functions

D
DebuggingDebugging compiled code
DESCRIPTION fileThe DESCRIPTION file
Details of R typesDetails of R types
Distribution functions from CDistribution functions
Documentation, writingWriting R documentation files
Dynamic loadingdyn.load and dyn.unload
dynamic pagesDynamic pages

E
Editing Rd filesEditing Rd files
encodingEncoding
Error handlingCondition handling and cleanup code
Error signaling from CError signaling
Error signaling from FortranError signaling from Fortran
Evaluating R expressions from CEvaluating R expressions from C
external pointerExternal pointers and weak references

F
Figures in documentationFigures
finalizerExternal pointers and weak references
Finding variablesFinding and setting variables

G
Gamma functionMathematical functions
Garbage collectionGarbage Collection
Generic functionsGeneric functions and methods

H
handling character dataHandling character data
Handling listsHandling lists
Handling R objects in CHandling R objects in C

I
IEEE special valuesMissing and special values
IEEE special valuesMissing and IEEE values
INDEX fileThe INDEX file
IndicesIndices
Inspecting R objects when debuggingInspecting R objects
integrationIntegration
Interfaces to compiled codeInterface functions .C and .Fortran
Interfaces to compiled codeInterface functions .Call and .External
Interfacing C++ codeInterfacing C++ code
InterruptsAllowing interrupts

L
LICENCE fileLicensing
LICENSE fileLicensing
Lists and tables in documentationLists and tables

M
Marking text in documentationMarking text
Mathematics in documentationMathematics
Memory allocation from CMemory allocation
Memory useProfiling R code for memory use
Method functionsGeneric functions and methods
Missing valuesMissing and special values
Missing valuesMissing and IEEE values

N
namespacesPackage namespaces
NEWS.Rd filePackage subdirectories
Numerical analysis subroutines from CNumerical analysis subroutines
Numerical derivativesCalculating numerical derivatives

O
OpenMPOpenMP support
OpenMPPlatform and version information
Operating system accessOperating system access
optimizationOptimization

P
Package builderBuilding package tarballs
Package structurePackage structure
Package subdirectoriesPackage subdirectories
PackagesCreating R packages
Parsing R code from CParsing R code from C
Platform-specific documentationPlatform-specific sections
Polygamma functionsMathematical functions
Printing from CPrinting
Printing from FortranPrinting from Fortran
Processing Rd formatProcessing documentation files
ProfilingProfiling R code for speed
ProfilingProfiling R code for memory use
ProfilingProfiling compiled code

R
Random numbers in CRandom numbers
Random numbers in CDistribution functions
Random numbers in FortranCalling C from Fortran and vice versa
Registering native routinesRegistering native routines

S
S4 objectsS4 objects
SerializationCustom serialization input and output
Setting variablesFinding and setting variables
Sort functions from CUtility functions
SweaveWriting package vignettes

T
tarballsBuilding package tarballs
Tidying R codeTidying R code

U
user-defined macrosUser-defined macros

V
Version information from CPlatform and version information
vignettesWriting package vignettes
VisibilityControlling visibility

W
weak referenceExternal pointers and weak references
Working with closuresWorking with closures

Z
Zero-findingZero-finding

Jump to:  .  
A  B  C  D  E  F  G  H  I  L  M  N  O  P  R  S  T  U  V  W  Z  

Footnotes

(1)

although this is a persistentmis-usage. It seems to stem from S, whose analogues of R’s packageswere officially known aslibrary sections and later aschapters, but almost always referred to aslibraries.

(2)

Thisseems to be commonly used for a file in ‘markdown’ format. Be awarethat most users of R will not know that, nor know how to view such afile: platforms such as macOS and Windows do not have a default viewerset in their file associations. TheCRAN package web pagesrender such files inHTML: the converter used expects the file to beencoded in UTF-8.

(3)

currently, top-level files.Rbuildignore and.Rinstignore, andvignettes/.install_extras.

(4)

false positives are possible, but only a handful have beenseen so far.

(5)

at least if thisis done in a locale which matches the package encoding.

(6)

and this formatis required byCRAN, so checked byR CMD check--as-cran if a ‘Date’ is provided

(7)

without asrc/Makefile* file.

(8)

LTO is not currently supported by the toolchainused on ‘aarch64’.

(9)

But it is checked for Open Source packagesbyR CMD check --as-cran.

(10)

Duplicate definitions maytrigger a warning: seeUser-defined macros.

(11)

bug.report will try to extract anemail address from aContact field if there is noBugReports field.

(12)

CRAN expands them to e.g.GPL-2| GPL-3.

(13)

even one wrapped in\donttest, or a demo script.

(14)

This includes all packagesdirectly called bylibrary andrequire calls, as well asdata obtainedviadata(theirdata, package = "somepkg")calls:R CMD check will warn about all of these. But thereare subtler uses which it may not detect: e.g. if package A usespackage B and makes use of functionality in package B which uses packageC which package B suggests or enhances, then package C needs to be inthe ‘Suggests’ list for package A. Nor will undeclared uses inincluded files be reported, nor unconditional uses of packages listedunder ‘Enhances’.R CMD check --as-cran will detect moreof the subtler uses.

(15)

Extensions.S and.s arise from code originally written for S(-PLUS),but are commonly used for assembler code. Extension.q was usedfor S, which at one time was tentatively called QPE.

(16)

but they should be in the encodingdeclared in theDESCRIPTION file.

(17)

This is true for OSes whichimplement the ‘C’ locale: Windows’ idea of the ‘C’ locale usesthe WinAnsi charset.

(18)

More precisely, they cancontain the English alphanumeric characters and the symbols‘$ - _ . + ! ' ( ) , ;  = &’.

(19)

either or both of which may not be supported on particularplatforms. Their main use is on macOS, but unfortunately recentversions of the macOSSDK have removed much of the support for ObjectiveC v1.0 and Objective C++.

(20)

This is not accepted by the Intel Fortran compiler.

(21)

Using.hpp is not guaranteedto be portable.

(22)

There is also ‘__APPLE_CC__’, but that indicates acompiler with Apple-specific features not the OS, although forhistorical reasons it is defined by LLVMclang. It isused inRinlinedfuns.h.

(23)

the POSIXterminology, called ‘make variables’ by GNU make.

(24)

As from R 4.5.0,R CMD check can beinvoked with option--run-demo to check demos analogously totests, including comparisons with optional reference outputs in.Rout.save files.

(25)

The best way to generate such a file is to copythe.Rout from a successful run ofR CMD check. If youwant to generate it separately, do run R with options--vanilla --no-echo and with environment variableLANGUAGE=en set to get messages in English. Be careful not to useoutput with the option--timings (and note that--as-cran sets it).

(26)

e.g.https://www.rfc-editor.org/rfc/rfc4180.

(27)

People who have trouble withcase are advised to use.rda as a common error is to refer toabc.RData asabc.Rdata!

(28)

For all theCRAN packages tested,eithergz orbzip2 provided a very substantial reductionin installed size.

(29)

BWidget’ still is on Windows but‘Tktable’ was not in R 4.0.0.

(30)

The scriptshould only assume a POSIX-compliant/bin/sh – seehttps://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html.In particularbash extensions must not be used, and not allR platforms have abash command, let alone one at/bin/bash. All known shells used with R support the use ofbackticks, but not all support ‘$(cmd)’. However, real-worldshells are not fully POSIX-compliant and omissions and idiosyncrasiesneed to be worked around—which Autoconf will do for you. Arithmeticexpansion is a known issue: seehttps://www.gnu.org/software/autoconf/manual/autoconf.html#Portable-Shellfor this and others. Some checks can be done by thecheckbashisms Perl script athttps://sourceforge.net/projects/checkbaskisms/files, alsoavailable in most Linux distributions in a package named either‘devscripts’ or ‘devscripts-checkbashisms’: a later versioncan be extracted from Debian sources such as the most recenttar.xz inhttps://deb.debian.org/debian/pool/main/d/devscripts/ and hasbeen needed for recent versions of Perl.

(31)

https://www.gnu.org/software/autoconf-archive/ax_blas.html. Ifyou include macros from that archive you need to arrange for them to beincluded in the package sources for use byautoreconf.

(32)

but it is available on themachines used to produce theCRAN binary packages: however asApple does not ship.pc files for its system libraries such asexpat,libcurl,libxml2,sqlite3 and‘zlib’, it may well not find information on these. Somesubstitutes are available fromhttps://github.com/R-macos/recipes/tree/master/stubs/pkgconfig-darwinand are installed on theCRAN package builders.

(33)

It is not wiseto check the version ofpkg-config as it is sometimes a linktopkgconf, a separate project with a different version series.

(34)

but not all projects get thisright when only a static library is installed, so it is often necessaryto try in turnpkg-config --libs andpkg-config--static --libs.

(35)

a decade ago Autoconf usedconfigure.in: this is still accepted but should be renamed andautoreconf as used byR CMD check --as-cran willreport as such.

(36)

For those usingautoconf 2.70 or later there is alsoAC_CONFIG_MACRO_DIRS which allows multiple directories to bespecified.

(37)

in POSIX parlance: GNUmakecalls these ‘make variables’.

(38)

at least on Unix-alikes: the Windows build currentlyresolves such dependencies to a static Fortran library whenRblas.dll is built.

(39)

https://www.openmp.org/,https://en.wikipedia.org/wiki/OpenMP,https://hpc-tutorials.llnl.gov/openmp/

(40)

There are somewhat fragile workarounds: seehttps://mac.r-project.org/openmp/.

(41)

Default builds of LLVMclang 3.8.0and later have support forOpenMP, but thelibomp run-timelibrary may not be installed.

(42)

In most implementations the_OPENMPmacro has value a date which can be mapped to anOpenMP version: forexample, value201307 is the date of version 4.0 (July2013). However this may be used to denote the latest version which ispartially supported, not that which is fully implemented.

(43)

Windows default, notMinGW-w64 default.

(44)

Which it was at the time of writing with GCC,Intel and Clang compilers. The count may include the threadrunning the main process.

(45)

Becareful not to declarenthreads asconst int: the Oraclecompiler required it to be ‘an lvalue’.

(46)

A few OSes (AIX, Windows) do notneed special flags for such code, but most do—although compilers willoften generate PIC code when not asked to do so.

(47)

Intel compilers do not by default but this is workedaround when using packages without asrc/Makefile.

(48)

but was said to havecomplete support only from version 2023.0.0.

(49)

Some changes are linkedfromhttps://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations:there were also additional deprecations.

(50)

Values201103L,201402L,201703Land202002L are most commonly used for C++11, C++14, C++17 andC++20 respectively, but some compilers set1L. For C++23 all thatcan currently be assumed is a value greater than that for C++20: forexampleg++ 12 uses202100L andclang++ (LLVM15, Apple 14) uses202101L.

(51)

Often historicallyused to mean ‘not C++98’

(52)

Seehttps://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendationsorhttps://en.cppreference.com/w/cpp/experimental/feature_test.It seems a reasonable assumption that any compiler promising some C++14conformance will provide these—e.g.g++ 4.9.x did but4.8.5 did not.

(53)

The latter has beenimplemented ingcc but not currently in LLVM nor Appleclang.

(54)

for examplegcc 14 and Appleclang 16, but notgcc 15, LLVMclang 18 andlater.

(55)

On systems which use sub-architectures,architecture-specific versions such as~/.R/check.Renviron.x64take precedence.

(56)

A suitablefile.exe ispart of the Windows toolset: it checks forgfile if a suitablefile is not found: the latter is available in the OpenCSWcollection for Solaris athttps://www.opencsw.org/. The sourcerepository ishttp://ftp.astron.com/pub/file/.

(57)

An exception is madefor subdirectories with names starting ‘win’ or ‘Win’.

(58)

on most other platforms such runtimelibraries are dynamic, but static libraries are currently used onWindows because the toolchain is not a standard part of the OS.

(59)

or if option--use-valgrind isused or environment variable_R_CHECK_ALWAYS_LOG_VIGNETTE_OUTPUT_is set to a true value or if there are differences from a target outputfile

(60)

for the mostcomprehensive checking this should be 5.8.0 or later: any for whichtidy --version does not report a version number will be tooold – this includes the 2006 version shipped with macOS.

(61)

For example, in early2014gdata declared ‘Imports: gtools’ andgtoolsdeclared ‘Imports: gdata’.

(62)

calledCVS or.svn or.arch-ids or.bzr or.git (but notfiles called.git) or.hg.

(63)

called.metadata.

(64)

which is an error: GNU make usesGNUmakefile.

(65)

seetools:::.hidden_file_exclusions andtools:::get_exclude_patterns() for furtherexcluded files and file patterns, respectively.

(66)

and to avoid problems with case-insensitive filesystems, lower-case versions of all these extensions.

(67)

unless inhibited by using‘BuildVignettes: no’ in theDESCRIPTION file.

(68)

provided the conditions of thepackage’s license are met: many, includingCRAN, see theomission of source components as incompatible with an Open Sourcelicense.

(69)

R_HOME/bin is prepended to thePATH so that references toR orRscript in theMakefile do make use of the currently running version of R.

(70)

Note thatlazy-loaded datasets arenot in the package’s namespace so needto be accessedvia::, e.g.survival::survexp.us.

(71)

they will be calledwith two unnamed arguments, in that order.

(72)

NB: this will only be read in all versions of R ifthe package contains R code in aR directory.

(73)

Note that this is thebasename of the shared object, and the appropriate extension (.soor.dll) will be added.

(74)

Imports: methods may suffice,but package code is little exercised without themethods packageon the search path and may not be fully robust to this scenario.

(75)

This defaults to the samepattern asexportPattern: use something likeexportClassPattern("^$") to override this.

(76)

if it does, there will be opaque warnings aboutreplacing imports if the classes/methods are also imported.

(77)

People usedev.new() to open adevice at a particular size: that is not portable but usingdev.new(noRStudioGD = TRUE) helps.

(78)

Solarismake did not acceptCRLF-terminated Makefiles; Solaris warned about and some othermakes ignore incomplete final lines.

(79)

This was apparentlyintroduced in SunOS 4, and is available elsewhereprovided it issurrounded by spaces.

(80)

GNU make,BSD make and other variants ofpmake in FreeBSD, NetBSD andformerly in macOS, and formerly AT&T make as implemented on Solaris and‘Distributed Make’ (dmake), part of Oracle Developer Studio andavailable in other versions including from Apache OpenOffice.

(81)

For example,testoptions-a and-e are not portable, and not supportedin the AT&T Bourne shell used on Solaris 10/11, even though they are inthe POSIX standard. Nor did Solaris support ‘$(cmd)’.

(82)

as fromR 4.0.0 the default isbash.

(83)

it was not in the Bourne shell, and was notsupported by Solaris 10.

(84)

https://fortranwiki.org/fortran/show/Modernizing+Old+Fortranmay help explain some of the warnings fromgfortran -Wall-pedantic.

(85)

or where supported the variants_Exit and_exit.

(86)

This andsrandom are in any case not portable. They are in POSIX but notin the C99 standard, and not available on Windows.

(87)

includingmacOS as from version 13.

(88)

inlibselinux.

(89)

At least Linux and Windows, but not macOS.

(90)

except perhaps the simplest kind as used bydownload.file() in non-interactive use.

(91)

Whereas the GNU linker reorders so-L optionsare processed first, the Solaris one did not.

(92)

some versions of macOS did not.

(93)

If a Java interpreter isrequired directly (notviarJava) this must be declaredand its presence tested like any other external command.

(94)

For example, the ability to handle ‘https://’URLs.

(95)

Notdoing so is the default on Windows, overridden for the Rexecutables.

(96)

These are not needed for the default compiler settingson ‘x86_64’ but are likely to be needed on ‘ix86’.

(97)

Select ‘Save as’, and select‘Reduce file size’ from the ‘Quartz filter’ menu’: this can be accessedin other ways, for example by Automator.

(98)

except perhaps somespecial characters such as backslash and hash which may be taken overfor currency symbols.

(99)

Typically on a Unix-alike this isdone by tellingfontconfig where to find suitable fonts toselect glyphs from.

(100)

Ubuntu provides 5 years of support (butpeople were running 14.04 after 7 years) and RHEL provides 10 years fullsupport and up to 14 with extended support.

(101)

This is seen on Linux, Solarisand FreeBSD, although each has other ways to turn on all extensions,e.g. defining_GNU_SOURCE,__EXTENSIONS__ or_BSD_SOURCE: the GCC compilers by default define_GNU_SOURCE unless a strict standard such as-std=c99 isused. On macOS extensions are declared unless one of these macros isgiven too small a value.

(102)

often taken fromthe toolchain’s headers.

(103)

at the time of writing ‘arm64’ macOS both warnedand did not supply a prototype inmath.h which resulted in acompilation error.

(104)

also part of C++11 and later.

(105)

which often is the same as the header included bythe C compiler, but some compilers have wrappers for some of the Cheaders.

(106)

Although this was addedfor C23, full support of that is years away.

(107)

https://stackoverflow.com/questions/32739018/a-replacement-for-stdbind2nd

(108)

it is allowedbut ignored in system headers.

(109)

an unsigned64-bit integer type on recent R platforms.

(110)

when using themacOS 13SDK with a deployment target of macOS 13.

(111)

and at one time as DEC Fortran, hence theDEC.

(112)

seehttps://gcc.gnu.org/gcc-10/porting_to.html.

(113)

Seehttps://prereleases.llvm.org/11.0.0/rc2/tools/clang/docs/ReleaseNotes.html#modified-compiler-flags.

(114)

In principle this coulddepend on the OS, but has been checked on Linux and macOS.

(115)

but C23 declaresthat header and the macro to be obsolescent.

(116)

discontinued in 2023.

(117)

There is a portable way to do this in Fortran 2003(ieee_is_nan() in moduleieee_arithmetic), but that wasnot supported in the versions 4.x of GNU Fortran. A pretty robustalternative is to testif(my_var /= my_var).

(118)

e.g.\alias,\keyword and\note sections.

(119)

There can be exceptions: for exampleRd files are not allowed to start with a dot, and have to beuniquely named on a case-insensitive file system.

(120)

in the current locale, and with specialtreatment for LaTeX special characters and with any‘pkgname-package’ topic moved to the top of the list.

(121)

\describe can still be used for more generallists, including when\item labels need special markup such as\var for metasyntactic variables, seeMarking text.

(122)

as defined by the R functiontrimws.

(123)

Currently it isrendered differently inHTML conversions, and in LaTeX and text conversionoutside ‘\usage’ and ‘\examples’ environments.

(124)

There is only a finedistinction between\dots and\ldots. It is technicallyincorrect to use\ldots in code blocks andtools::checkRdwill warn about this—on the other hand the current converters treatthem the same way in code blocks, and elsewhere apart from the smalldistinction between the two in LaTeX.

(125)

See theexamples section in the fileParen.Rd for an example.

(126)

R2.9.0 added support for UTF-8 Cyrillic characters in LaTeX, but onsome OSes this will need Cyrillic support added to LaTeX, soenvironment variable_R_CYRILLIC_TEX_ may need to be set to anon-empty value to enable this.

(127)

Rhas to be built to enable this, but the option--enable-R-profiling is the default.

(128)

For Unix-alikes by default these are intervalsof CPU time, and for Windows of elapsed (‘wall-clock’) time. As fromR 4.4.0, elapsed time is optional on Unix-alikes

(129)

With the exceptions of the commandslisted below: an object of such a name can be printedvia anexplicit call toprint.

(130)

The macOS support is for long-obsoleteversions.

(131)

in somedistributions packaged separately, for example asvalgrind-devel.

(132)

Those in some numeric, logical,integer, raw, complex vectors and in memory allocated byR_alloc.

(133)

including using the data sections of R vectors afterthey are freed.

(134)

smallfixed-size arrays by default ingfortran, for example.

(135)

currently on ‘x86_64’/‘ix86’Linux and FreeBSD, with some support for macOS – seehttps://developer.apple.com/documentation/xcode/diagnosing-memory-thread-and-crash-issues-early. (Thereis a faster variant, HWASAN, for ‘aarch64’ only.) On someplatforms the runtime library,libasan, needs to be installedseparately, and for checking C++ you may also needlibubsan.

(136)

seehttps://llvm.org/devmtg/2014-04/PDFs/LightningTalks/EuroLLVM%202014%20--%20container%20overflow.pdf.

(137)

part of the LLVM project anddistributed inllvmRPMs and.debs on Linux. It is notcurrently shipped by Apple.

(138)

as Ubuntu has been said todo.

(139)

installed on some Linux systems asasan_symbolize, and obtainable fromhttps://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/asan/scripts/asan_symbolize.py:it makes use ofllvm-symbolizer if available.

(140)

includinggcc 7.1 andclang 4.0.0: forgcc it is implied by-fsanitize=address.

(141)

forexample, X11/GL libraries on Linux, seen when checking packagergl and some others using it—a workaround is to setenvironment variableRGL_USE_NULL=true.

(142)

On someplatforms the runtime library,libubsan, needs to be installedseparately. For macOS, seehttps://developer.apple.com/documentation/xcode/diagnosing-memory-thread-and-crash-issues-early.

(143)

butworks better if inlining and frame pointer optimizations are disabled.

(144)

By default as a security measure: seeman dyld.

(145)

Seehttps://svn.r-project.org/R-dev-web/trunk/CRAN/QA/Simon/R-build/fixpathR:‘@executable_path’ could be used rather than absolute paths.

(146)

possibly after some platform-specifictranslation, e.g. adding leading or trailing underscores.

(147)

This is currently included byR.h but may not be in future, so it should be included by codeneeding the type.

(148)

Note that this is then not checked for over-runs byoptionCBoundsCheck = TRUE.

(149)

Strictly this is OS-specific, but no exceptions havebeen seen for many years.

(150)

For calls from within a namespace the search is confined tothe DLL loaded for that package.

(151)

For unregistered entry points the OS’sdlsymroutine is used to find addresses. Its performance varies considerablyby OS and even in the best case it will need to search a much largersymbol table than, say, the table of.Call entry points.

(152)

Because it is a standardpackage, one would need to rename it before attempting to reproduce theaccount here.

(153)

generally those with an ELF linker and macOSfrom R 4.5.0.

(154)

whether or not ‘LinkingTo’ is used.

(155)

so there needs to be a correspondingimport orimportFrom entry in theNAMESPACE file.

(156)

Even including C system headers insuch a block has caused compilation errors.

(157)

https://en.wikipedia.org/wiki/Application_binary_interface.

(158)

Forexample, ‘_GLIBCXX_USE_CXX11_ABI’ ing++ 5.1 and later:https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_dual_abi.html.

(159)

dyld on macOS,andDYLD_LIBRARY_PATHS below.

(160)

That is,similar to those defined in S version 4 from the 1990s: these arenot kept up to date and are not recommended for new projects.

(161)

seeThe RAPI: entry points for C code: note that these are not all part ofthe API.

(162)

SEXP is an acronym forSimpleEXPression, common in LISP-like language syntaxes.

(163)

If no coercion was required,Rf_coerceVector wouldhave passed the old object through unchanged.

(164)

You can assign acopy of the object in theenvironment framerho usingdefineVar(symbol,duplicate(value), rho)).

(165)

This is only guaranteed to show thecurrent interface: it is liable to change.

(166)

Known problems have beendefiningLENGTH,error,length,match,vector andwarning: whether these matter depends on the OSand toolchain, with many problem reports involving Apple or LLVMclang++.

(167)

That was notthe case on Windows prior to R 4.2.0.

(168)

also part ofC++11.

(169)

The ‘F77_’ in the names is historical anddates back to usage in S.

(170)

It is an optional C11extension.

(171)

Most compilers do not check valueswhen assigning to anenum and store this type as anint,so this may appear to work now but it likely to fail in future.

(172)

https://en.wikipedia.org/wiki/Endianness.

(173)

Not pre-2023 Intel norAIX norSolaris compilers.

(174)

This applies to thecompiler for the default C++ dialect and not necessarily to otherdialects.

(175)

In many cases Fortran compilers accept the flag butdo not actually hide their symbols: at the time of writing that was trueofgfortran,flang and Intel’sifx.

(176)

In the parlance of macOSthis is adynamic library, and is the normal way to build R onthat platform.

(177)

but theseare not part of the automated test procedures and so little tested.

(178)

At least according toPOSIX 2004 and later. Earlier standards prescribedsys/time.h:R_ext/eventloop.h will include it ifHAVE_SYS_TIME_H isdefined.

(179)

at least on platforms where the values areavailable, that is havinggetrlimit and on Linux or havingsysctl supportingKERN_USRSTACK, including FreeBSD andmacOS.

(180)

Anattempt to use only threads in the late 1990s failed to work correctlyunder Windows 95, the predominant version of Windows at that time.


[8]ページ先頭

©2009-2025 Movatter.jp