Movatterモバイル変換


[0]ホーム

URL:


CRANStatusBadgeCRAN RStudio mirror downloadsCRAN RStudio mirror downloadsR-CMD-checkDOI

Rdpack provides functions for manipulation of R documentationobjects, including functionsreprompt() andereprompt() for updating existing Rd documentation forfunctions, methods and classes; Rd macros for citations and import ofreferences frombibtex files for use inRdfiles androxygen2 comments (\insertRef,\insertCite,\insertAllCited); Rd macros forevaluating and inserting snippets of R code and the results of itsevaluation (\printExample) or creating graphics on the fly(\insertFig); and many functions for manipulation ofreferences and Rd files.

Table of Contents

  1. Installing Rdpack
  2. Inserting Bibtex references and citations
    1. Preparation
    2. Inserting references
    3. Inserting citations
    4. Changing the style of references
    5. Troubleshooting
      1. A puzzling message in devtools developmentmode
      2. Typical errors
    6. Latex markup in BibTeX entries
    7. Encoding of file REFERENCES.bib
  3. Viewing Rd files
  4. Using Rdpack::reprompt()
    1. What it does
    2. Reprompt and open in an editor
  5. Inserting evaluated examples
    1. Evaluating the examples in sectionExamples
  6. Inserting figures/graphs/plots

Installing Rdpack

Install thelatest stableversion from CRAN:

install.packages("Rdpack")

You can also install thedevelopment version ofRdpack from Github:

library(devtools)install_github("GeoBosh/Rdpack")

Inserting Bibtexreferences and citations

The simplest way to insert Bibtex references is with the Rd macro\insertRef. Just put\insertRef{key}{package}in the documentation to insert item with keykey from fileREFERENCES.bib in your packagepackage.Alternatively, use one or more\insertCite{key}{package}commands to cite works fromREFERENCES.bib, then issue asingle\insertAllCited{} directive to produce a list of allcited references. For this to work theDESCRIPTION file ofthe package needs to be amended, see below the full details.

Preparation

To prepare a package for importing BibTeX references it is necessaryto tell the package management tools that package Rdpack and its Rdmacros are needed. The references should be put in fileinst/REFERENCES.bib. These steps are enumerated below insomewhat more detail, see also the vignetteInserting_bibtex_references.

  1. Add the following lines to file “DESCRIPTION”:

    Imports: RdpackRdMacros: Rdpack

    Make sure the capitalisation ofRdMacros: is as shown.If the fieldRdMacros: is already present, add “Rdpack” tothe list on that line. Similarly for field “Imports:”.

  2. Add the following line to file “NAMESPACE”:

    importFrom(Rdpack,reprompt)

    The equivalent line forroxygen2 is

    #' @importFrom Rdpack reprompt
  3. Create fileREFERENCES.bib in subdirectoryinst/ of your package and put the BibTeX references init.

Inserting references

Once the steps outlined above are done, references can be inserted inthe documentation as

\insertRef{key}{package}

wherekey is the bibtex key of the reference andpackage is your package. This works inRdfiles and inroxygen documentation chunks.

Usually references are put in sectionreferences. In anRd file this might look something like:

\references{\insertRef{Rdpack:bibtex}{Rdpack}\insertRef{R}{bibtex}}

The equivalentroxygen2 documentation chunk wouldbe:

#' @references#' \insertRef{Rpackage:rbibutils}{Rdpack}#'#' \insertRef{R}{bibtex}

The first line above inserts the reference with keyRpackage:rbibutils in Rdpack’s REFERENCES.bib. The secondline inserts the reference labeledR in file REFERENCES.bibfrom packagebibtex.

The example above demonstrates that references from other packagescan be inserted (in this casebibtex), as well. This isstrongly discouraged for released versions but is convenient duringdevelopment. One relatively safe use is when the other package is alsoyours - this allows authors of multiple packages to not copy the samerefences to each of their own packages.

For further details see the vignetteInserting_bibtex_referencesor open it fromR:

vignette("Inserting_bibtex_references", package = "Rdpack")

(The latest version of the vignette is atInserting_bibtex_references (development version on github).)

Inserting citations

Additional Rd macros are available for citations. They also can beused in both Rd and roxygen2 documentation.

\insertCite{key}{package} citeskey andrecords it for use by\insertAllCited and\insertCited, see below.key can contain morekeys separated by commas.

\insertCite{parseRd,Rpackage:rbibutils}{Rdpack} produces(Murdoch 2010; Boshnakov and Putman 2020) and\insertCite{Rpackage:rbibutils}{Rdpack} gives (Boshnakovand Putman 2020).

By default the citations are parenthesised:\insertCite{parseRd}{Rdpack} produces (Murdoch 2010). Toget textual citations, like Murdoch (2010), put the string;textual at the end of the key. The references in the lasttwo sentences would be produced with\insertCite{parseRd}{Rdpack} and\insertCite{parseRd;textual}{Rdpack}, respectively. Thisalso works with several citations, e.g.

\insertCite{parseRd,Rpackage:rbibutils;textual}{Rdpack}produces: Murdoch (2010); Boshnakov and Putman (2020).

The macro\insertNoCite{key}{package} records one ormore references for\insertAllCited but does not cite it.Settingkey to* will include all referencesfrom the specified package. For example,\insertNoCite{R}{bibtex} and\insertNoCite{*}{utils} record the specified references forinclusion by\insertAllCited.

\insertAllCited inserts all references cited with\insertCite or\insertNoCite. Putting thismacro in the references section will keep it up to date automatically.The Rd section may look something like:

\insertAllCited{}

or, in roxygen2, the references chunk might look like this:

#' @references#'   \insertAllCited{}

Don’t align the backslash with the second ‘e’ of@references, since roxygen2 may interpret it as verbatimtext, not macro.

\insertCited{} works like\insertAllCitedbut empties the reference list after finishing its work. This means thatthe second and subsequent\insertCited in the same helppage will list only citations done since the preceding\insertCited. Prompted by issue 27 on github to allowseparate reference lists for each method and the class in R6documentation.

To mix the citations with other text, such as ``see also’’ and``chapter 3’’, write the list of keys as a free text, starting it withthe symbol@ and prefixing each key with it. The@ symbol will not appear in the output. For example, thefollowing code

\insertCite{@see also @parseRd and @Rpackage:rbibutils}{Rdpack}\insertCite{@see also @parseRd; @Rpackage:rbibutils}{Rdpack}\insertCite{@see also @parseRd and @Rpackage:rbibutils;textual}{Rdpack}

produces:

(see also Murdoch 2010 and Boshnakov and Putman 2020)

(see also Murdoch 2010; Boshnakov and Putman 2020)

see also Murdoch (2010) and Boshnakov and Putman (2020)

With the parenthesised citations, if you need markup for the textbefore or after the citations, saysee also in italic, put;nobrackets1at the end of the first argument of the Rd macro, take out the partcontaining markup, and put the parentheses were suitable. Forexample,

(\emph{see also} \insertCite{@@parseRd and @Rpackage:rbibutils;nobrackets}{Rdpack})

(in markdown, use_see also_ in place of\emph{see also}). This gives:

(see also Murdoch 2010 and Boshnakov and Putman 2020)

\insertCiteOnly{key}{package} is as\insertCite but does not include the key in the list ofreferences for\insertAllCited.

Changing the style ofreferences

Bibliography styles for lists of references are supported fromRdpack (>= 0.8). Currently the only alternative offered is touse long names (Georgi N. Boshnakov) in place of the default style(Boshnakov GN). More comprehensive alternatives can be included ifneeded or requested.

To cause all lists of references produced by\insertAllCited in a package to appear with full names, add.onLoad() function to your package. If you don’t have.onLoad(), just copy the following definition:

.onLoad <- function(lib, pkg){    Rdpack::Rdpack_bibstyles(package = pkg, authors = "LongNames")    invisible(NULL)}

If you already have.onLoad(), add the line containingtheRdpack::Rdpack_bibstyles call to it.

After installling/reloading your package the lists of referencesshould appear with long author names. “Rdpack” itself now uses thisstyle.

Troubleshooting

A puzzlingmessage in devtools development mode

The described procedure works transparently inroxygen2chunks and with Hadley Wickham’s packagedevtools. Packagesare built and installed properly with thedevtools commandsand the references are processed as expected.

Currently (2017-08-04) if you run help commands?xxx forfunctions from the package you are working onin developementmode and their help pages contain references, you may encountersome puzzling warning messages, something like:

1: In tools::parse_Rd(path) :  ~/mypackage/man/abcde.Rd: 67: unknown macro '\insertRef'

These warnings are harmless and can be ignored — the help pages arebuilt properly and no warnings appear outsidedeveloper’s mode,e.g. in a separate Rsession2. Evenbetter, use the functionviewRd() described below to viewthe required help file.

Typical errors

The functions underlying the processing of references and citationsintercept errors, such as missing BibTeX labels or badly formed items inREFERENCES.bib, and issue informative warnings during the building andinstallation of the package, so that the developer is alerted but thepackage can still be built and installed. In these cases the functionsusually insert a suitable text in the documentation, as well. If youencounter a situation contradicting this description, it is probably abug — please report it (but check first for the typical errors listedbelow).

A non-decipherable error message is probably caused by one of thefollowing typical errors:

These errors occur during parsing of the Rd files, before the controlis passed to theRdpack’s macros.

Latex markup in BibTeXentries

In principle, BibTeX entries may contain arbitrary Latex markup,while the Rd format supports only a subset. As a consequence, someBibTeX entries may need some editing when included inREFERENCES.bib3.Only do this for entries that do not render properly or cause errors,since most of the time this should not be necessary.

If mathematics doesn’t render properly replace the Latex dollarsyntax with Rd’s\eqn, e.g. $x^2$ with\eqn{x^2}. This should not be needed for versions of Rdpack0.8-4 or later.

Some Latex macros may have to be removed or replaced with suitable Rdmarkup. Again, do this only if they cause problems, since some aresupported, e.g. \doi.

See also the overview help page,help("Rdpack-package"),of package"Rdpack". Among other things, it contains somedummy references which illustrate the above.

Encoding of fileREFERENCES.bib

If a package has a declared encoding (in fileDESCRIPTION),REFERENCES.bib is read-in withthatencoding4.Otherwise, the encoding ofREFERENCES.bib is assumed to beUTF-8 (which includes ASCII as a subset).

Note that BibTeX entries downloaded from online databases and similarsources may contain unexpected characters in other encodings,e.g. ‘latin1’. In such cases the check tools in R-devel (since about2018-10-01) may give warnings like:

prepare_Rd: input string 1 is invalid in this locale

To resolve this, convert the file to the declared encoding or UTF-8.Alternatively, replace the offending symbols with their classicTeX/LaTeX equivalents (which are ASCII). Non-ASCII symbols in BibTeXentries obtained from online databases are often in fields like“Abstract”, which are normally not included in lists of references andcan be deleted from REFERENCES.bib.

One way to check for non-ASCII symbols in a file istools::showNonASCIIfile().

Internally, LaTeX sequences standing for accented Latin characters,such as\'e and\"o, are converted to UTF-8.So, even if the file REFERENCES.bib is pure ASCII, it may implicitlygive raise to non-ASCII characters. This may cause R’s checking tools tocomplain about non-ASCII characters even after it has been verified thatthere are none. If this happens, add the encoding declaration to fileDESCRIPTION5:

Encoding: UTF-8

Needless to say, make sure that there are really no characters fromencodings like ‘latin1’.

Viewing Rd files

The functionviewRd() can be used to view Rd files inthe source directory of apackage6. Atypical user call would look something like:

Rdpack::viewRd("./man/filename.Rd")

The requested help page is shown in the default format for thecurrent R session (taken fromgetOption("help_type")). Torequest a specific format settype to"html"or"text", as in:

Rdpack::viewRd("./man/filename.Rd", type = "html") # open in a browserRdpack::viewRd("./man/filename.Rd", type = "text") # text

viewRd() renders references and citations correctly,since it processes Rd macros.

Users of ‘devtools’ can useviewRd in place ofhelp() to view rendered Rd sources in development mode.This should work also in development mode on any platform (e.g. RStudio,Emacs/ESS,Rgui)7.

Using Rdpack::reprompt()

What it does

Rdpack::reprompt() updatesRddocumentation. In the most common case when it is called on anRd file, it updates the documentation of all functions,methods and classes documented in the file. For functions this includesupdating the usage section, adding missing aliases and\item’s for arguments not described yet. For methods andclasses entries for new methods and slots are updated in a similar way.See the documentation for details.

Rdpack::reprompt() can also be invoked on an object orthe name of an object, just asutils::prompt. In that caseit checks for installed documentation for the object and works on it iffound. Otherwise it creates anRd file with initial contentsimilar to the one generated byutils::prompt but modifiedso that the package can be built.

If a new function, saynewfun is to be documented in anexisting Rd file, just addnewfun() to the usage section inthe file and callRdpack::reprompt() to insert the correctusage statement, add an alias, and add items for any new arguments. Putquotes around the function name if it is non-syntactic. For replacementfunctions (functions with names ending in<-)reprompt() will insert the proper usage statement. Forexample, if the signature ofxxx<- is(x, ..., value), then both,"xxx<-"() andxxx() <- value will be replaced byxxx(x, ...) <- value.

Rdpack::reprompt()does not removeanything that has become obsolete but it alerts the user to removealiases, methods, and descriptions of arguments that have beenremoved.

Reprompt and open in aneditor

To open thereprompt()-ed file, argumentedit can be used. For this to work,options("editor") needs to be set suitably but it usuallyis. Ifedit = TRUE, thenRdpack::reprompt()will open the Rd file in an editor. For more convenient access to thisfeature, useRdpack::ereprompt() (edit reprompt), whichcallsRdpack::reprompt() withedit = TRUE andsets the output filename to be the same as the input filename.

In RStudio,reprompt() can be invoked on theRd file being edited or the selected name of an object in asource code file using RStudio add-inRepropmpt(contributed by Duncan Murdoch). Obviously, this makes sense only for Rdfiles not generated byroxygen2.

In Emacs/ESS there are various ways to useRdpack::reprompt() andRdpack::ereprompt(). Ifoptions("editor") is set toemacsclient,Rdpack::ereprompt is one option. It can also be assigned toa key (wrapped in Elisp code), for example to be invoked on thecurrently edited file. Such a function and example key binding can befound atgeorgisemacs.

Inserting evaluated examples

Rdpack provides a macro that takes a chunk of R code,evaluates it, and includes both the code and the results in the rendereddocumentation. The layout is similar to that in the R console but thecode is not prefixed with anything and the output is prefixed withcomment symbols. For example,

\printExample{2+2; a <- 2*3; a}

gives

2 + 2##: 4a <- 2 * 3a##: 6

The help page of?Rdpack::promptUsage contains a numberof examples created with\printExample. The correspondingRd file can be obtained from the package tarball or fromhttps://github.com/GeoBosh/Rdpack/blob/master/man/promptUsage.Rd.

VignetteInserting_figures_and_evaluated_examplesgives further details.

Evaluating theexamples in section Examples

The macro\runExamples can be used as a replacement ofsectionexamples. For example, if the following code is putat the top level in an Rd file (i.e. not in a section):

\runExamples{2+2; a <- 2*3; a}

then it will be evaluated and replaced by a normal sectionexamples:

\examples{2 + 2##: 4a <- 2 * 3a##: 6}

This generated examples section is processed by the standard R tools(almost) as if it was there from the outset. In particular, the examplesare run by the R’s quality control tools and tangled along with examplesin other documentationfiles8. Asmall example package using this feature is atrunExamplesCheck.

Insertingfigures/graphs/plots

Figures can be inserted with the help of the standard Rd markupcommand\figure. To generate figures on the fly, package"Rdpack" provides the Rd macro\insertFigwhich takes a snipped of R code, evaluates it and inserts the plotproduced by it (using\figure).\insertFigtakes three arguments: a filename, the package name and the code toevaluate to produce the figure. For example,

\insertFig{cars.png}{mypackage}{x <- cars$speed; y <- cars$dist; plot(x,y)}

will evaluate the code, save the graph in file"man/figures/cars.png" subdirectory of package"mypackage", and include the figure using\figure.

See vignetteInserting_figures_and_evaluated_examplesfor more details.

Footnotes

1 FromRdpack (> 2.1.3) (prompted by Martin R. Smith, issue#23).

2 If you care, here is whathappens. These warnings appear becausedevtools reroutesthe help command to process the developer’s Rd sources (rather than thedocumentation in the installed directory) but doesn’t tellparse_Rd where to look for additional macros. Indeed, themessage above shows that the error is in processing a source Rd file inthe development directory of the package and that the call toparse_Rd specifies only the file.

3 Thanks to Michael Deweyfor suggesting the discussion of this.

4 FromRdpack (>=0.9-1) The issue of not handling the encodingwas raised by Professor Brian Ripley.

5 Admittedly, this is notideal since the user should not need to care how things are processedinternally but I haven’t pinpointed the exact cause for this.

6 FromRdpack (>= 0.4-23).

7 In recent versions ofRstudio this function is no longer needed, since?fun nowhandles the macros.

8 In versions ofR before3.6.0 the macro\runExamples may causeR CMD check to give awarning warning about unknown\Sexpr section at toplevel.


[8]ページ先頭

©2009-2025 Movatter.jp