diff --git a/.github/workflows/code-quality.yml b/.github/workflows/code-quality.yml index e58bb33..06dbc7d 100644 --- a/.github/workflows/code-quality.yml +++ b/.github/workflows/code-quality.yml @@ -23,14 +23,21 @@ jobs: uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd - name: Lint workflow YAML - run: | - python3 -m pip install --user yamllint - python3 -m yamllint .yamllint.yml .github/dependabot.yml .github/workflows/*.yml + uses: ibiqlik/action-yamllint@2576378a8e339169678f9939646ee3ee325e845c + with: + file_or_dir: .yamllint.yml .github/dependabot.yml .github/workflows/*.yml - name: Lint markdown docs - run: | - npm install -g markdownlint-cli2@0.18.1 - markdownlint-cli2 README.md AGENTS.md ARCHITECTURE.md CLAUDE.md CONTRIBUTING.md .github/**/*.md docs/**/*.md + uses: DavidAnson/markdownlint-cli2-action@6bf21b07787794f89a243495939cd651942aeabe + with: + globs: | + README.md + AGENTS.md + ARCHITECTURE.md + CLAUDE.md + CONTRIBUTING.md + .github/**/*.md + docs/**/*.md - name: Lint GitHub workflows run: | diff --git a/.gitignore b/.gitignore index b7e79ba..bb7c3c1 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,8 @@ task_agent_mapping.json # local package build artifacts aFIPC_*.tar.gz + +# generated packrat libraries (restore from packrat.lock + packrat/src) +packrat/lib/ +packrat/lib-R/ +packrat/lib-ext/ diff --git a/AGENTS.md b/AGENTS.md index b60b03d..ac28b37 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -60,17 +60,17 @@ Applies to every agent (Claude, Codex, Cursor, opencode, ...) working in this re fixable only). It runs against each PR base, **including stacked PRs**. - A failing `trivy-fs` is a **REAL finding, not a flake.** Read the job log (it prints each finding's rule id, severity, and file) or the run's SARIF results, - then **remediate**: bump the offending R dependency (this package vendors its - library tree under `packrat/`), or, only for a genuine false positive, add a + then **remediate**: bump the offending tracked dependency source under + `packrat/src`, or, only for a genuine false positive, add a narrow, path-scoped, commented entry to `.trivyignore.yaml`. Never weaken or disable the gate. This repo has no Dockerfile or k8s manifests, so misconfig findings are not expected; a hit here is a dependency or secret finding. -- The vendored packrat openssl docs include a verified false-positive example - key at `packrat/lib/x86_64-pc-linux-gnu/3.4.1/openssl/doc/keys.html`; keep - its `private-key` suppression path-scoped in `.trivyignore.yaml` and do not - blanket-ignore the rule. +- Generated `packrat/lib`, `packrat/lib-R`, and `packrat/lib-ext` trees are + ignored and must never be committed; `packrat/init.R` restores them from the + tracked lock file and source cache. - A local `trivy` scan with a stale DB misses findings: run - `trivy --download-db-only` first, and scan the **merge ref**, not just the PR head. + `trivy --download-db-only` first, and scan the **merge ref**, not just the PR + head. - The org `code_scanning` ruleset is intentionally **CodeQL-only** (multiple code-scanning tools cannot converge on one PR ref). Gating is by the Security Scan **job result**, not the `code_scanning` rule; do not add tools to that rule. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 3880f15..815a591 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -12,7 +12,8 @@ metadata and CI are wired, and which parts are safe to evolve. - `DESCRIPTION` - Package metadata (name, version, imports, license) - `NAMESPACE` - Export map for package functions - `man/` - Generated R documentation (`.Rd` files) -- `packrat/` - Historical dependency lock/vendor directory +- `packrat/` - Historical dependency lock and source cache. The installed + `packrat/lib` tree is generated locally, ignored, and never committed. - `.github/workflows/` - CI + security automation - `.github/SECURITY.md` - Vulnerability reporting policy - `.github/PULL_REQUEST_TEMPLATE.md` - PR review checklist template diff --git a/CLAUDE.md b/CLAUDE.md index 264efb1..22afcfb 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -74,7 +74,8 @@ See `ARCHITECTURE.md` for the full map. Essentials: imports `mirt` and `methods` (`DESCRIPTION`). - `man/` — generated `.Rd` docs for the exported functions. - `tests/testthat/` — testthat suite, driven by `tests/testthat.R`. -- `packrat/` — historical vendored dependency tree; opt-in only. +- `packrat/` — historical dependency lock and source cache; opt-in only. The + generated `packrat/lib` installation tree is ignored and never committed. - `.github/workflows/` — `r.yml` (R CMD check), `code-quality.yml` (yamllint + markdownlint + actionlint), `security-audit.yml` (gitleaks + actionlint). All action refs are pinned to full commit SHAs. @@ -106,9 +107,9 @@ Summarized from `AGENTS.md` and `CONTRIBUTING.md`; read those for detail. `confirmCommonItems = TRUE` in non-interactive contexts (the tests assert that implicit approval fails). - A failing `trivy-fs` in the Security Scan gate is a real finding, not a - flake: bump the offending vendored dependency under `packrat/`, or add a - narrow, path-scoped, commented entry to `.trivyignore.yaml`. Never weaken - the gate. (`trivy.yaml` skips `packrat/lib` for local scans.) + flake: bump the offending tracked dependency source under `packrat/src`, or + add a narrow, path-scoped, commented entry to `.trivyignore.yaml`. Never + weaken the gate. Generated `packrat/lib` content must remain untracked. - New copyleft dependencies (GPL/AGPL/LGPL) are not accepted; never commit secrets. - Use the PR template (`.github/PULL_REQUEST_TEMPLATE.md`): include risk diff --git a/README.md b/README.md index 7e5816f..6073077 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,8 @@ preserve numerical behavior while modernizing repository operations - `R/aFIPC.R`: core `autoFIPC()` implementation - `DESCRIPTION`, `NAMESPACE`, `man/`: package metadata and generated docs -- `packrat/`: historical dependency lock/vendor directory +- `packrat/`: historical dependency lock and source cache; restored libraries + are generated locally and not tracked - `.github/workflows/`: CI/security automation ## Development status @@ -19,7 +20,8 @@ preserve numerical behavior while modernizing repository operations - Algorithmic core is legacy but trusted for historical outputs. - Operational guardrails are now maintained via GitHub Actions and Dependabot. - Legacy `packrat` bootstrap is opt-in via `AFIPC_ENABLE_PACKRAT=true`. -- Broken host-specific `packrat/lib-R` symlinks were removed for portable builds. +- `packrat/init.R` can rebuild the ignored `packrat/lib` tree from the tracked + lock file and source cache; host-specific installed binaries are not committed. - Architectural and agent operation docs are available in: - `ARCHITECTURE.md` - `AGENTS.md` diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/CITATION b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/CITATION deleted file mode 100644 index 85cd31c..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/CITATION +++ /dev/null @@ -1,20 +0,0 @@ -citHeader("To cite package 'GPArotation' in publications use:") - -citEntry(entry="article", - author = personList(as.person("Coen A. Bernaards"), - as.person("Robert I.Jennrich")), - year = 2005, - title = "Gradient Projection Algorithms and Software for Arbitrary - Rotation Criteria in Factor Analysis", - journal = "Educational and Psychological Measurement", - volume = "65", - pages = "676--696", - - textVersion = - paste("Bernaards, Coen A. and Jennrich, Robert I. (2005) ", - "Gradient Projection Algorithms and Software for Arbitrary", - "Rotation Criteria in Factor Analysis, ", - "Educational and Psychological Measurement: 65, 676-696. ", - "", - sep="") - ) diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/DESCRIPTION b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/DESCRIPTION deleted file mode 100644 index 6dc5627..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/DESCRIPTION +++ /dev/null @@ -1,19 +0,0 @@ -Package: GPArotation -Version: 2014.11-1 -Title: GPA Factor Rotation -Description: Gradient Projection Algorithm Rotation for Factor - Analysis. See ?GPArotation.Intro for more details. -Depends: R (>= 2.0.0) -LazyLoad: yes -License: GPL (>= 2) | file LICENSE -Author: Coen Bernaards and Robert Jennrich -Maintainer: Paul Gilbert -URL: http://www.stat.ucla.edu/research/gpa -Packaged: 2014-11-24 17:21:12 UTC; paul -NeedsCompilation: no -Repository: CRAN -Date/Publication: 2014-11-25 08:40:16 -Built: R 3.4.1; ; 2017-09-09 18:08:12 UTC; unix -InstallAgent: packrat 0.4.8.38 -InstallSource: CRAN -Hash: 4821625833bcab5af24257ead9119e01 diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/INDEX b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/INDEX deleted file mode 100644 index d639c21..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/INDEX +++ /dev/null @@ -1,10 +0,0 @@ -00.GPArotation.Intro GPA Rotation for Factor Analysis -GPArotation-package GPA Rotation for Factor Analysis -GPForth Rotation Optimization -Harman Example Data from Harman -Random.Start Generate a Random Orthogonal Rotation -Thurstone Example Data from Thurstone -WansbeekMeijer Factor Example from Wansbeek and Meijer -echelon Echelon Rotation -eiv Errors-in-Variables Rotation -rotations Rotations diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/LICENSE b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/LICENSE deleted file mode 100644 index c6638a8..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/LICENSE +++ /dev/null @@ -1,2 +0,0 @@ -Copyright 2005-2006, Coen Bernaards and Robert Jennrich -License: GPL Version 2 or later. diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/Rd.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/Rd.rds deleted file mode 100644 index a18b569..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/Rd.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/data.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/data.rds deleted file mode 100644 index 563979f..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/data.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/features.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/features.rds deleted file mode 100644 index 2027d3f..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/features.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/hsearch.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/hsearch.rds deleted file mode 100644 index 16484d2..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/hsearch.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/links.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/links.rds deleted file mode 100644 index ef1b5f7..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/links.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/nsInfo.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/nsInfo.rds deleted file mode 100644 index 9e08336..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/nsInfo.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/package.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/package.rds deleted file mode 100644 index b4a3ae3..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/package.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/vignette.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/vignette.rds deleted file mode 100644 index 01c732c..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/Meta/vignette.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/NAMESPACE b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/NAMESPACE deleted file mode 100644 index bf3a9ca..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/NAMESPACE +++ /dev/null @@ -1,38 +0,0 @@ -export( - "GPFoblq", - "GPForth") - -export("Random.Start") - -export("oblimin") -export("quartimin") -export("targetT") -export("targetQ") -export("pstT") -export("pstQ") -export("oblimax") -export("entropy") -export("quartimax") -export("Varimax") -export("simplimax") -export("bentlerT") -export("bentlerQ") -export("tandemI") -export("tandemII") -export("geominT") -export("geominQ") -export("cfT") -export("cfQ") -export("infomaxT") -export("infomaxQ") -export("mccammon") -export("bifactorT") -export("bifactorQ") - -export( - "eiv", - "echelon") - -S3method("print", "GPArotation") -S3method("summary", "GPArotation") -S3method("print", "summary.GPArotation") diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/NEWS b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/NEWS deleted file mode 100644 index d82ce8d..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/NEWS +++ /dev/null @@ -1,91 +0,0 @@ -Known problems - - o Very occassionally (about 1 in 1000 in monte carlo experiments) the - algorithm gets stuck and does not improve (so does not converge). The - workaround is to restart with a very slightly perturbed starting point. - -Changes in GPArotation version 2014.11-1 - - o Minor format and cleanup required by CRAN checks, no real changes. - -Changes in GPArotation version 2012.3-1 - - o no real changes, but bumping version for new CRAN suitability check. - -Changes in GPArotation version 2011.11-1 - - o updated maintainer email address. - -Changes in GPArotation version 2011.10-1 - - o Modification to vgQ.target to allow NA in target, which is replaced by - 0.0 (from William Revelle). - - o Added bifactorT and bifactorQ (biquartimin) from William Revelle. - -Changes in GPArotation version 2010.07-1 - - o Fix an error caused by an exact initial setting (from William Revelle). - -Changes in GPArotation version 2009.02-2 - - o Standardized NEWS format for new function news(). - - -Changes in GPArotation version 2009.02-1 - - o minor documentation corrections as found by a new R-devel. - - -Changes in GPArotation version 2008.05-1 - - o added echelon rotation. - - o added gradient Gq to result list from GPForth and GPFoblq. - - o change license from "GPL-2" to "GPL-2 or later". - - -Changes in GPArotation version 2007.06-1 - - o fixed a couple of lingering $Lh (in print and summary methods) that should - have been changed to $loadings. - - -Changes in GPArotation version 2007.04-1 - - o removed an extra comma in c() that caused a test failure with R-2.5.0 - - o added eiv rotation. - - o renamed $Lh in the result from GPForth and GPFoblq to $loadings. As a - result, rotation methods calling these function no longer need to rename - this element in order to work with factanal and other programs. (It is a - good idea to use the extractor function loadings() rather than refer - directly to object structure.) - - o changed rotation method functions to return all elements of GPFoblq and - GFForth. - - o fixed the documentation file primary alias for all rotations (which was - being called oblimin). - - -Changes in GPArotation version 2006.2-2 - - o extra argument (...) to invisible in print.GPArotation was removed. - - -Changes in GPArotation version 2006.2-1 - - o broken references in documentation were fixed and updated. - - -Changes in GPArotation version 2005.10-1 - - o warning message about non-convergence expanded to indicate function. - - -GPArotation version 2005.4-1 - - o First released version. diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/R/GPArotation b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/R/GPArotation deleted file mode 100644 index 3b65e3c..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/R/GPArotation +++ /dev/null @@ -1,27 +0,0 @@ -# File share/R/nspackloader.R -# Part of the R package, http://www.R-project.org -# -# Copyright (C) 1995-2012 The R Core Team -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# A copy of the GNU General Public License is available at -# http://www.r-project.org/Licenses/ - -local({ - info <- loadingNamespaceInfo() - pkg <- info$pkgname - ns <- .getNamespace(as.name(pkg)) - if (is.null(ns)) - stop("cannot find namespace environment for ", pkg, domain = NA); - dbbase <- file.path(info$libname, pkg, "R", pkg) - lazyLoad(dbbase, ns, filter = function(n) n != ".__NAMESPACE__.") -}) diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/R/GPArotation.rdb b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/R/GPArotation.rdb deleted file mode 100644 index 104e8e8..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/R/GPArotation.rdb and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/R/GPArotation.rdx b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/R/GPArotation.rdx deleted file mode 100644 index d3deda0..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/R/GPArotation.rdx and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/data/Harman.rda b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/data/Harman.rda deleted file mode 100644 index fa058b6..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/data/Harman.rda and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/data/Thurstone.rda b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/data/Thurstone.rda deleted file mode 100644 index 01c2f93..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/data/Thurstone.rda and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/data/WansbeekMeijer.rda b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/data/WansbeekMeijer.rda deleted file mode 100644 index 93eb86e..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/data/WansbeekMeijer.rda and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/doc/Guide.Stex b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/doc/Guide.Stex deleted file mode 100644 index 85b315e..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/doc/Guide.Stex +++ /dev/null @@ -1,35 +0,0 @@ -\documentclass[english]{article} -\begin{document} - -%\VignetteIndexEntry{gpa Guide} -\SweaveOpts{eval=TRUE,echo=TRUE,results=hide,fig=FALSE} -\begin{Scode}{echo=FALSE,results=hide} - options(continue=" ") -\end{Scode} - -\section{GPArotation Functions} -In R, the functions in this package are made available with -\begin{Scode} -library("GPArotation") -\end{Scode} - -The most complete reference for the software is: -Bernaards, C.A. and Jennrich, R.I. (in press) Gradient Projection Algorithms -and Software for Arbitrary Rotation Criteria in Factor Analysis. Educational -and Psychological Measurement. Addition material is also available at -. - -Rotations are computed using the Gradient Projection Algorithm code, which can -be called directly. Examples of this are available in the help pages for -\emph{GPForth} and \emph{GPFoblq}. In R it may be most convenient to pass -the rotation name to the factanal program. An example of this is - -\begin{Scode} - data(ability.cov) - z <- factanal(factors = 2, covmat = ability.cov, rotation="oblimin") - loadings(z) -\end{Scode} - -Other examples are available in the help page for \emph{rotations}. - -\end{document} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/doc/Guide.pdf b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/doc/Guide.pdf deleted file mode 100644 index 602147f..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/doc/Guide.pdf and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/doc/index.html b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/doc/index.html deleted file mode 100644 index d6a695f..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/doc/index.html +++ /dev/null @@ -1,28 +0,0 @@ - - -R: Vignettes and other documentation - - - -

Vignettes and other documentation - -

-
-
-[Top] -
-

Vignettes from package 'GPArotation'

- ------- - - - - -
GPArotation::Guidegpa GuidePDFsourceR code
- diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/AnIndex b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/AnIndex deleted file mode 100644 index 585ae15..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/AnIndex +++ /dev/null @@ -1,61 +0,0 @@ -GPArotation-package GPArotation-package -00.GPArotation.Intro 00.GPArotation.Intro -bentlerQ rotations -bentlerT rotations -bifactorQ rotations -bifactorT rotations -box20 Thurstone -box26 Thurstone -cfQ rotations -cfT rotations -echelon echelon -eiv eiv -entropy rotations -geominQ rotations -geominT rotations -GPArotation.Intro GPArotation-package -GPFoblq GPA -GPForth GPA -Harman Harman -Harman8 Harman -infomaxQ rotations -infomaxT rotations -mccammon rotations -NetherlandsTV WansbeekMeijer -NormalizingWeight NormalizingWeight -oblimax rotations -oblimin rotations -print.GPArotation print.GPArotation -print.summary.GPArotation print.GPArotation -pstQ rotations -pstT rotations -quartimax rotations -quartimin rotations -Random.Start Random.Start -rotations rotations -simplimax rotations -summary.GPArotation print.GPArotation -tandemI rotations -tandemII rotations -targetQ rotations -targetT rotations -Thurstone Thurstone -Varimax rotations -vgQ.bentler rotations -vgQ.bifactor rotations -vgQ.cf rotations -vgQ.entropy rotations -vgQ.geomin rotations -vgQ.infomax rotations -vgQ.mccammon rotations -vgQ.oblimax rotations -vgQ.oblimin rotations -vgQ.pst rotations -vgQ.quartimax rotations -vgQ.quartimin rotations -vgQ.simplimax rotations -vgQ.tandemI rotations -vgQ.tandemII rotations -vgQ.target rotations -vgQ.varimax rotations -WansbeekMeijer WansbeekMeijer diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/GPArotation.rdb b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/GPArotation.rdb deleted file mode 100644 index 4a4c793..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/GPArotation.rdb and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/GPArotation.rdx b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/GPArotation.rdx deleted file mode 100644 index 6825436..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/GPArotation.rdx and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/aliases.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/aliases.rds deleted file mode 100644 index e308c44..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/aliases.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/paths.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/paths.rds deleted file mode 100644 index 1098d22..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/help/paths.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/html/00Index.html b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/html/00Index.html deleted file mode 100644 index 37ba315..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/html/00Index.html +++ /dev/null @@ -1,140 +0,0 @@ - - -R: GPA Factor Rotation - - - -

GPA Factor Rotation - -

-
-
-[Up] -[Top] -

Documentation for package ‘GPArotation’ version 2014.11-1

- - - -

Help Pages

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
GPArotation-packageGPA Rotation for Factor Analysis
00.GPArotation.IntroGPA Rotation for Factor Analysis
bentlerQRotations
bentlerTRotations
bifactorQRotations
bifactorTRotations
box20Example Data from Thurstone
box26Example Data from Thurstone
cfQRotations
cfTRotations
echelonEchelon Rotation
eivErrors-in-Variables Rotation
entropyRotations
geominQRotations
geominTRotations
GPArotation.IntroGPA Rotation for Factor Analysis
GPFoblqRotation Optimization
GPForthRotation Optimization
HarmanExample Data from Harman
Harman8Example Data from Harman
infomaxQRotations
infomaxTRotations
mccammonRotations
NetherlandsTVFactor Example from Wansbeek and Meijer
oblimaxRotations
obliminRotations
pstQRotations
pstTRotations
quartimaxRotations
quartiminRotations
Random.StartGenerate a Random Orthogonal Rotation
rotationsRotations
simplimaxRotations
tandemIRotations
tandemIIRotations
targetQRotations
targetTRotations
ThurstoneExample Data from Thurstone
VarimaxRotations
vgQ.bentlerRotations
vgQ.bifactorRotations
vgQ.cfRotations
vgQ.entropyRotations
vgQ.geominRotations
vgQ.infomaxRotations
vgQ.mccammonRotations
vgQ.oblimaxRotations
vgQ.obliminRotations
vgQ.pstRotations
vgQ.quartimaxRotations
vgQ.quartiminRotations
vgQ.simplimaxRotations
vgQ.tandemIRotations
vgQ.tandemIIRotations
vgQ.targetRotations
vgQ.varimaxRotations
WansbeekMeijerFactor Example from Wansbeek and Meijer
- diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/html/R.css b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/html/R.css deleted file mode 100644 index f10f5ea..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/html/R.css +++ /dev/null @@ -1,97 +0,0 @@ -body { - background: white; - color: black; -} - -a:link { - background: white; - color: blue; -} - -a:visited { - background: white; - color: rgb(50%, 0%, 50%); -} - -h1 { - background: white; - color: rgb(55%, 55%, 55%); - font-family: monospace; - font-size: x-large; - text-align: center; -} - -h2 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-size: large; - text-align: center; -} - -h3 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-size: large; -} - -h4 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-style: italic; - font-size: large; -} - -h5 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; -} - -h6 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-style: italic; -} - -img.toplogo { - width: 4em; - vertical-align: middle; -} - -img.arrow { - width: 30px; - height: 30px; - border: 0; -} - -span.acronym { - font-size: small; -} - -span.env { - font-family: monospace; -} - -span.file { - font-family: monospace; -} - -span.option{ - font-family: monospace; -} - -span.pkg { - font-weight: bold; -} - -span.samp{ - font-family: monospace; -} - -div.vignettes a:hover { - background: rgb(85%, 85%, 85%); -} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Harman.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Harman.R deleted file mode 100644 index e513bfc..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Harman.R +++ /dev/null @@ -1,181 +0,0 @@ -#Example from: Gradient Projection Algorithms and Software for -# Arbitrary Rotation Criteria in Factor Analysis. -# by Coen A. Bernaards and Robert I. Jennrich -# Website: http://www.stat.ucla.edu/research - - Sys.getenv("R_LIBS") - library() - require("GPArotation") - search() - Sys.info() - - -fuzz <- 1e-5 # using eps=1e-5 these tests do not do better than this -all.ok <- TRUE - -# quartimax (orthogonal) rotation of Harman's 8 physical variables. - -data("Harman", package="GPArotation") - -qHarman <- GPForth(Harman8, Tmat=diag(2), method="quartimax") -qHarman2 <- quartimax(Harman8) - - if( fuzz < max(abs(qHarman$loadings - qHarman2$loadings))) { - cat("Calculated value is not the same as test value in test Harman 1. Value:\n") - print(qHarman$loadings, digits=18) - cat("difference:\n") - print(qHarman$loadings - qHarman2$loadings, digits=18) - all.ok <- FALSE - } - -#qHarman$Th - qHarman2$Th - -# with eps=1e-8 -# tst <- t(matrix(c( -# 0.898754567491920398, 0.194823580226859222, -# 0.933943406208487592, 0.129748657024604030, -# 0.902131483644799892, 0.103864268239045668, -# 0.876508251941102934, 0.171284220753554678, -# 0.315572019798302239, 0.876476069451083251, -# 0.251123191235179066, 0.773488941629975613, -# 0.198007116064591759, 0.714678376605717203, -# 0.307857241091366252, 0.659334451631046314 -# ), 2, 8)) - -# with eps=1e-5 - tst <- t(matrix(c( - 0.898755404698461491, 0.194819718009510034, - 0.933943963768413821, 0.129744643590955028, - 0.902131929972106672, 0.103860391510923730, - 0.876508987992224209, 0.171280454135453869, - 0.315575786273609882, 0.876474713336210853, - 0.251126515144778573, 0.773487862471829213, - 0.198010187248201075, 0.714677525703678707, - 0.307860074444663512, 0.659333128670876345 - ), 2, 8)) - - if( fuzz < max(abs(qHarman$loadings - tst ))) { - cat("Calculated value is not the same as test value in test Harman 2. Value:\n") - print(qHarman$loadings, digits=18) - cat("difference:\n") - print(qHarman$loadings - tst, digits=18) - all.ok <- FALSE - } - -# with eps=1e-8 -# tst <- t(matrix(c( -# 0.790828307905322436, 0.612038060430562525, -# -0.612038060430562525, 0.790828307905322214 -# ), 2, 2)) - -# with eps=1e-5 - tst <- t(matrix(c( - 0.790830938007507367, 0.612034662000581764, - -0.612034662000581764, 0.790830938007507145 - ), 2, 2)) - - if( fuzz < max(abs(qHarman$Th - tst ))) { - cat("Calculated value is not the same as test value in test Harman 3. Value:\n") - print(qHarman$Th, digits=18) - cat("difference:\n") - print(qHarman$Th - tst, digits=18) - all.ok <- FALSE - } - - - - - -# quartimin (oblique) rotation of Harman's 8 physical variables. - -qminHarman <- GPFoblq(Harman8, Tmat=diag(2), method="quartimin") -qminHarman2 <- quartimin(Harman8) - - if( fuzz < max(abs(qminHarman$loadings - qminHarman2$loadings))) { - cat("Calculated value is not the same as test value in test Harman 4. Value:\n") - print(qminHarman$loadings, digits=18) - cat("difference:\n") - print(qminHarman$loadings - qminHarman2$loadings, digits=18) - all.ok <- FALSE - } - - -# with eps=1e-8 -# tst <- t(matrix(c( -# 0.8918217697289939627, 0.0560146456758183961, -# 0.9536799985772628219, -0.0232460005406671701, -# 0.9291498623396581280, -0.0465027396531852502, -# 0.8766828510822184395, 0.0336582451338717017, -# 0.0136988312985193428, 0.9250013826349388069, -# -0.0172668087945964319, 0.8212535444941218010, -# -0.0524468998178311899, 0.7649536381341245361, -# 0.0858880630098148856, 0.6831160953442911854 -# ),2, 8)) - -# with eps=1e-5 - tst <- t(matrix(c( - 0.8918219293548808047, 0.0560145122875230911, - 0.9536799846795966928, -0.0232460559140742311, - 0.9291497958388006406, -0.0465027685653178480, - 0.8766829604751505967, 0.0336581364763500201, - 0.0137008854716444972, 0.9250004106413580729, - -0.0172649861805529957, 0.8212526839806429946, - -0.0524452035885302342, 0.7649528396536503516, - 0.0858895830186393733, 0.6831153711863455769 - ),2, 8)) - - if( fuzz < max(abs(qminHarman$loadings - tst ))) { - cat("Calculated value is not the same as test value in test Harman 5. Value:\n") - print(qminHarman$loadings, digits=18) - cat("difference:\n") - print(qminHarman$loadings - tst, digits=18) - all.ok <- FALSE - } - - -# with eps=1e-8 -# tst <- t(matrix(c( -# 1.000000000000000000, 0.472747617396915065, -# 0.472747617396915065, 1.000000000000000000 -# ),2, 2)) - -# with eps=1e-5 - tst <- t(matrix(c( - 1.000000000000000222, 0.472745958387102538, - 0.472745958387102538, 1.000000000000000000 - ),2, 2)) - - if( fuzz < max(abs(qminHarman$Phi - tst ))) { - cat("Calculated value is not the same as test value in test Harman 6. Value:\n") - print(qminHarman$Phi, digits=18) - cat("difference:\n") - print(qminHarman$Phi - tst, digits=18) - all.ok <- FALSE - } - - -# with eps=1e-8 -# tst <- t(matrix(c( -# 0.878125245495924522, 0.836723841642554422, -# -0.478430823863515542, 0.547625065922776710 -# ),2, 2)) - -# with eps=1e-5 - tst <- t(matrix(c( - 0.878125280760480686, 0.836722770276292271, - -0.478430759137962514, 0.547626702874473570 - ),2, 2)) - - if( fuzz < max(abs(qminHarman$Th - tst ))) { - cat("Calculated value is not the same as test value in test Harman 7. Value:\n") - print(qminHarman$Th, digits=18) - cat("difference:\n") - print(qminHarman$Th - tst, digits=18) - all.ok <- FALSE - } - - -cat("tests completed.\n") - -if (! all.ok) stop("some tests FAILED") - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Jennrich2002.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Jennrich2002.R deleted file mode 100644 index d77d8b3..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Jennrich2002.R +++ /dev/null @@ -1,120 +0,0 @@ -# test by William Revelle -# from Jennrich, Psychometrika, 2002, solution for the Thurstone 20 box problem. # Specifying 27 elements to be 0 as discussed in that article (Table 1 at -# page 12) and using vgQ.target as revised or vgQ.pst with a W matrix -# and Target as specified does not yield the reported solution. -# The solution is almost identical for the high loadings but differs slightly -# for the small loadings. The two models have a factor congruence of .99 for -# all three factors, but do not agree completely. - -# Jennrich (2002) apparently was using the oblique rotation option. -# When running TargetQ the results are fine, or when running -# the vgQ.pst function with GPFoblq. - -# This a good test case for both TargetQ -# (It could also be adapted for pst but there is already a test for it.) - -require("GPArotation") -data(Thurstone) #the 20 box problem - -#solution reported in Jennrich 2002 - -browne <- t(matrix(c( - 0.013, 0.994, 0.007, - 0.991, 0.012, 0.001, - 0.018, 0.003, 0.986, - 0.772, 0.477, 0.002, - 0.003, 0.393, 0.874, - 0.409, 0.003, 0.816, - 0.548, 0.730, -0.020, - 0.023, 0.870, 0.405, - 0.799, -0.024, 0.453, - 0.664, 0.621, -0.005, - -0.058, 0.915, 0.512, - 0.639, -0.018, 0.644, - 0.046, 0.980, -0.003, - 0.971, -0.038, 0.060, - -0.026, 0.025, 0.965, - 0.380, 0.281, 0.726, - 0.490, 0.652, 0.286, - -0.025, 0.971, 0.019, - 0.957, 0.061, -0.045, - 0.028, 0.000, 0.976), - 3,20,dimnames = list(c("B1", "B2", "B3"), NULL))) - -#a simplified target matrix, with NAs for ? and 0 for 0s. -# (compare to pst appproach) -Target <- t(matrix(c( - 0, NA, 0, - NA, 0, 0, - 0, 0, NA, - NA, NA, 0, - 0, NA, NA, - NA, 0, NA, - NA, NA, 0, - 0, NA, NA, - NA, 0, NA, - NA, NA, 0, - 0, NA, NA, - NA, 0, NA, - 0, NA, 0, - NA, 0, 0, - 0, 0, NA, - NA, NA, NA, - NA, NA, NA, - 0, NA, 0, - NA, 0, 0, - 0, 0, NA), - 3, 20, dimnames = list(c("T1", "T2", "T3"), NULL))) - -v <- targetQ(box20,Target=Target)$loadings - -all.ok <- TRUE - -#slightly larger fuzz for comparison with published value. -# note max(abs(v) - abs(browne))rather than max(abs(v - browne)) -# as sign change is possible - if( 10e-4 < max(abs(v) - abs(browne))) { - cat("Calculated value is not the same as test value in Jennrich2002. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - browne, digits=18) - all.ok <- FALSE - } - -good <- t(matrix(c( - 0.01324194563970146343, -0.99360765277094842407, 0.007265459960371034587, - 0.99121314541487770544, -0.01178320700232154961, 0.000654586020267855506, - 0.01798447315534307256, -0.00266076852016330911, 0.985581004768931734361, - 0.77198435084052174915, -0.47723548341238952730, 0.001547735983967568618, - 0.00334198654247502835, -0.39290416948063611180, 0.874043793719835537814, - 0.40934347835281348349, -0.00274610551094590233, 0.815649888720176186041, - 0.54757055519984310088, -0.72951044925148011977, -0.020211353947714422175, - 0.02292379053779741716, -0.87011712730189194609, 0.404542252780873523577, - 0.79911058029224457666, 0.02416810475294199623, 0.452727043944761764482, - 0.66393502364020362538, -0.62149665012300570055, -0.005186928343372421146, - -0.05839790682548451350, -0.91517931889838155524, 0.511521949806932663130, - 0.63924406199386740735, 0.01841750353525576159, 0.643544196342115570886, - 0.04597086497418309547, -0.97980801598321454193, -0.002918643110053173451, - 0.97103389549392915558, 0.03847065084578840666, 0.060066450372699808913, - -0.02622776344285615568, -0.02482060086975104718, 0.965272709232911085842, - 0.37998105522582992233, -0.28073835673932595602, 0.726047993725112084107, - 0.48985182554738604388, -0.65226812910595410866, 0.285738966726349907788, - -0.02451057644240206557, -0.97122042802717223342, 0.019132901654980147277, - 0.95708220223038309449, -0.06086293722346142188, -0.045050942196376064786, - 0.02797903728304645954, 0.00036458752733534161, 0.976083771686937051726), - 3,20,dimnames = list(c("B1", "B2", "B3"), NULL))) - -#tighter fuzz for numerical comparison with previous test value - if( 10e-12 < max(abs(v - good))) { - cat("Calculated value is not the same as previous test value. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - good, digits=18) - all.ok <- FALSE - } - - -cat("tests completed.\n") - - -if (! all.ok) stop("some tests FAILED") diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/MASSoblimin.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/MASSoblimin.R deleted file mode 100644 index d07b45f..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/MASSoblimin.R +++ /dev/null @@ -1,80 +0,0 @@ - - Sys.getenv("R_LIBS") - library() - require("GPArotation") - search() - Sys.info() - -#require("stats") - -fuzz <- 1e-6 -all.ok <- TRUE - - -# test MASS 4th ed. p 322-324 - - data(ability.cov) - ability.cov - ability.FA <- factanal(factors = 1, covmat=ability.cov) - - (ability.FA <- update(ability.FA, factors = 2)) - -# ability.FA2 <- factanal(factors = 2, covmat = ability.cov) -# max(abs(ability.FA2$loadings - ability.FA$loadings)) - -# summary(ability.FA) MASS ed.4 p 323 seems to be print not summary in R 2.0.1 - ability.FA - -# this is default varimax rotation. There are 3rd+ digit differences with MASS - tst <- t(matrix(c( - 0.499437829039896530, 0.54344904693111962, - 0.156070079431279873, 0.62153798991197484, - 0.205786989958578748, 0.85992588538426895, - 0.108530754440558652, 0.46776101732283504, - 0.956242470279811574, 0.18209631992182243, - 0.784768183877880943, 0.22482213687364205 - ), 2, 6)) - - - if( fuzz < max(abs(loadings(ability.FA) - tst))) { - cat("Calculated value is not the same as test value in test 1. Value:\n") - #print(loadings(ability.FA), digits=18) this truncates - print(unclass(ability.FA$loadings), digits=18) - cat("difference:\n") - print(unclass(ability.FA$loadings) - tst, digits=18) - all.ok <- FALSE - } - - - # differences with MASS here are a bit more than might be expected, - # but there is already a difference before rotation. - (oblirot <- oblimin(loadings(ability.FA))) - - obli2 <- factanal(factors = 2, covmat = ability.cov, rotation="oblimin") - - max(abs(loadings(oblirot) - loadings(obli2))) - - -# factanal(factors = 2, covmat = ability.cov, scores = Bartlett, rotation="oblimin") - - - tst <- t(matrix(c( - 0.3863637969729337152, 0.4745113977203344047, - -0.0110032278171669998, 0.6458708261423832253, - -0.0262888675561207576, 0.8961123879025085781, - -0.0180180060207963122, 0.4882918937716873575, - 0.9900948712271664398, -0.0370729040114848238, - 0.7905663749272058283, 0.0526099352008769991 - ), 2, 6)) - - if( fuzz < max(abs(loadings(oblirot) - tst ))) { - cat("Calculated value is not the same as test value in test 2. Value:\n") - print(loadings(oblirot), digits=18) - cat("difference:\n") - print(loadings(oblirot) - tst, digits=18) - all.ok <- FALSE - } - -cat("tests completed.\n") - -if (! all.ok) stop("some tests FAILED") diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Revelle.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Revelle.R deleted file mode 100644 index cab3682..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Revelle.R +++ /dev/null @@ -1,21 +0,0 @@ -# This tests fix for an error caused by an exact initial setting. -# (from William Revelle) - -require("GPArotation") - -f3 <- structure(c(0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0,0), - .Dim = c(6L, 3L), .Dimnames = list(NULL, c("PC1", "PC2", "PC3"))) - -f3 - -# PC1 PC2 PC3 -#[1,] 0 0 1 -#[2,] 0 1 0 -#[3,] 1 0 0 -#[4,] 0 0 1 -#[5,] 0 1 0 -#[6,] 1 0 0 - -# These previously gave object 'VgQt' not found -GPForth(f3) -Varimax(f3) diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Thurstone.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Thurstone.R deleted file mode 100644 index 0708e5c..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/Thurstone.R +++ /dev/null @@ -1,324 +0,0 @@ -#Example from: Gradient Projection Algorithms and Software for -# Arbitrary Rotation Criteria in Factor Analysis. -# by Coen A. Bernaards and Robert I. Jennrich -# Website: http://www.stat.ucla.edu/research - - Sys.getenv("R_LIBS") - library() - require("GPArotation") - search() - Sys.info() - - data("Thurstone", package="GPArotation") - if (!exists("box20")) stop("Test data not found. Testing stopped.") - -fuzz <- 1e-5 -all.ok <- TRUE - -# Thurstone's box problem. (1947, p. 136) -# The matrix box20 is the initial loading matrix from Thurstone's box problem. - -# This takes a lot of iterations to converge at a higher tolerance -qbox20 <- quartimax(box20, eps=1e-5) -qbox20G <- GPForth(box20, Tmat=diag(1,3), method="quartimax", eps=1e-5) - - if( fuzz < max(abs(qbox20$loadings - qbox20G$loadings))) { - cat("Calculated value is not the same as test value in test Thurstone 1. Value:\n") - print(qbox20$loadings - qbox20G$loadings, digits=18) - cat("difference:\n") - print(qbox20$loadings - tst, digits=18) - all.ok <- FALSE - } - -#qbox20$Th - qbox20G$Th - -# These values compare with those in: -# http://www.stat.ucla.edu/research/web.pdf - tst <- t(matrix(c( - 0.0104916072210123716, -0.993396087928394733, -0.089861775335686706, - 0.1584646383898045685, -0.167305085570175344, -0.967087879524061056, - 0.9822741057703969769, -0.094961339079248266, -0.081938545344928893, - 0.1249962020162782989, -0.597065497283680413, -0.789290657131387352, - 0.8695614167874907707, -0.471622450093366785, -0.090438968384549553, - 0.8757114893176747294, -0.141012080768234127, -0.452333925937943637, - 0.0679423211019681700, -0.811411071716238719, -0.588554936857709099, - 0.4066768108416509708, -0.907862149146695163, -0.115673202040957226, - 0.5770808894249742638, -0.142370726163931066, -0.806527261406603468, - 0.1012712863762783577, -0.723336747696182614, -0.694640249329106285, - 0.5000928657774492692, -0.949746569049947253, -0.046846346456817907, - 0.7412589798326677526, -0.140350561965914555, -0.663578062154924320, - 0.0055655501003109590, -0.983847100401775698, -0.120037109608235590, - 0.2142330103903098415, -0.119429100752156334, -0.947421187831809397, - 0.9550804066106526324, -0.108275659756619305, -0.039227521113362487, - 0.7823218737697450464, -0.405437596810190704, -0.439275358874331168, - 0.3626971102221024923, -0.753122462957226402, -0.546281394544768872, - 0.0162483298780003657, -0.966230359337758582, -0.052114148464710915, - 0.1076692386876715729, -0.206734953950642314, -0.934620775424686911, - 0.9744239420161749932, -0.092650552854598708, -0.090828719474599584 - ), 3, 20)) - - if( fuzz < max(abs(qbox20$loadings - tst ))) { - cat("Calculated value is not the same as test value in test Thurstone 2. Value:\n") - print(qbox20$loadings, digits=18) - cat("difference:\n") - print(qbox20$loadings - tst, digits=18) - all.ok <- FALSE - } - - tst <- t(matrix(c( - 0.57232345894276127, -0.60751194947821441, -0.55079496147384377, - 0.60249460283341838, 0.76716797198365361, -0.22012168525406509, - 0.55627880770383020, -0.20587018726291534, 0.80509089803322043 - ), 3, 3)) - - if( fuzz < max(abs(qbox20$Th - tst ))) { - cat("Calculated value is not the same as test value in test Thurstone 3. Value:\n") - print(qbox20$Th, digits=18) - cat("difference:\n") - print(qbox20$Th - tst, digits=18) - all.ok <- FALSE - } - - -# sorted absolute loading plots. -sal <- abs(c(loadings(qbox20)))[order(abs(c(loadings(qbox20))))] -plot(seq(length(sal)), sal) - - - #compare quartimax rotation of the initial loading matrix box20. - - if( fuzz < max(abs(loadings(qbox20) - box20 %*% qbox20$Th ))) { - cat("Calculated value is not the same as test value in test Thurstone 4. Value:\n") - print(loadings(qbox20), digits=18) - cat("difference:\n") - print(loadings(qbox20) - box20 %*% qbox20$Th, digits=18) - all.ok <- FALSE - } - - - -qminbox20G <- GPFoblq(box20, Tmat=diag(1,3), method="quartimin", eps=1e-5) -qminbox20 <- quartimin(box20, eps=1e-5) - - if( fuzz < max(abs(loadings(qminbox20) - qminbox20G$loadings))) { - cat("Calculated value is not the same as test value in test Thurstone 5. Value:\n") - print(qminbox20G$loadings , digits=18) - cat("difference:\n") - print(loadings(qminbox20) - qminbox20G$loadings, digits=18) - all.ok <- FALSE - } - -#qminbox20$Th - quartimin(box20)$Th - -# These values compare with those in: -# http://www.stat.ucla.edu/research/web.pdf - tst <- t(matrix(c( - -0.099561899210599963, -1.0236437309424475384, 0.017110338313848200, - -0.007103778102200991, 0.0427848301281630802, -1.009962780073245581, - 1.012864497258948226, 0.0331727792925069487, 0.050367710973030555, - -0.054843850612513692, -0.4493155290974688021, -0.772334543778026350, - 0.856287122381722998, -0.3740197232441037078, 0.069350368268248391, - 0.835580575619599641, 0.0487450425576793633, -0.360381644212301344, - -0.102893671454670210, -0.7226715938020771279, -0.537456650126404090, - 0.322103633211960838, -0.8816846447967544576, 0.031159743715387874, - 0.462799683447739529, 0.0852338438217692257, -0.783762970578423479, - -0.076585435689138226, -0.6043060025891554554, -0.658295846696152820, - 0.427772530893690217, -0.9288687512327726825, 0.122866182561916254, - 0.659408232467282085, 0.0772080094990600374, -0.607348040513722709, - -0.108761719100651882, -1.0079608432113262850, -0.017378089000366713, - 0.059518597564186392, 0.0955950614351480238, -0.986779686330629513, - 0.989890866913205381, 0.0071520817823045348, 0.094691644950703049, - 0.713733277219835149, -0.2427293600063723522, -0.328268187306521242, - 0.220344503737931546, -0.6353746612195683152, -0.459661643730432223, - -0.084703580704062989, -1.0022284232457450148, 0.055740317456252478, - -0.059151779416785115, -0.0113377397453605679, -0.976867596293413132, - 1.003360458549731771, 0.0365098037316876067, 0.039427150580815938 - ), 3, 20)) - - if( fuzz < max(abs(qminbox20G$loadings - tst ))) { - cat("Calculated value is not the same as test value in test Thurstone 6. Value:\n") - print(qminbox20G$loadings, digits=18) - cat("difference:\n") - print(qminbox20G$loadings - tst, digits=18) - all.ok <- FALSE - } - - tst <- t(matrix(c( - 1.00000000000000000, -0.25676300454795098, -0.32155119431295237, - -0.25676300454795098, 1.00000000000000000, 0.33656790396842257, - -0.32155119431295237, 0.33656790396842257, 1.00000000000000000 - ), 3, 3)) - - if( fuzz < max(abs(qminbox20G$Phi - tst ))) { - cat("Calculated value is not the same as test value in test Thurstone 7. Value:\n") - print(qminbox20G$Phi, digits=18) - cat("difference:\n") - print(qminbox20G$Phi - tst, digits=18) - all.ok <- FALSE - } - - -#To fuzz precision the rotated loading matrix and the factor cor- -#relation matrix phi are identical to those produced using the oblique GP -#algorithm with exact derivatives. - - if( fuzz < max(abs(qminbox20G$Phi - - t(qminbox20G$Th )%*% qminbox20G$Th ))) { - cat("Calculated value is not the same as test value in test Thurstone 8. Value:\n") - print(qminbox20G$Phi, digits=18) - cat("difference:\n") - print(qminbox20G$Phi - - t(qminbox20G$Th )%*% qminbox20G$Th, digits=18) - all.ok <- FALSE - } - - #compare quartimin rotation of the initial loading matrix box20. - if( fuzz < max(abs(qminbox20G$loadings - box20 %*% solve(t(qminbox20G$Th))))) { - cat("Calculated value is not the same as test value in test Thurstone 9. Value:\n") - print(qminbox20G$loadings, digits=18) - cat("difference:\n") - print(qminbox20G$loadings - box20 %*% solve(t(qminbox20G$Th)), digits=18) - all.ok <- FALSE - } - - data("box26", package="GPArotation") - if (!exists("box26")) stop("Test data box26 not found. Testing stopped.") - -qbox26 <- GPForth(box26, Tmat=diag(1,3), method="quartimax", eps=1e-5) - - tst <- t(matrix(c( - 0.6245197355925140581, -0.2708954695931116152, 0.7151983951389878635, - 0.7386116884036847408, 0.6266342260884526505, -0.0617439911892987553, - 0.7803093788467402314, -0.3830982859243221017, -0.4578886072022986253, - 0.8540550453155928423, 0.2886436985992582027, 0.4062915145925659610, - 0.8810593765418006651, -0.4428658074662961130, 0.1233946983666596581, - 0.9084731768740617053, 0.1540526132602804965, -0.3723026715563940159, - 0.8150592858039771293, 0.0441965358534676597, 0.5600768044145943980, - 0.8466584455973064083, 0.4551177395514792168, 0.1889929089788950356, - 0.8156808837280125069, -0.4090629943132625956, 0.3690652552112651530, - 0.9629492340906220527, -0.4781483041690369196, -0.0866081507974762743, - 0.8731366884896356595, 0.3451069860590937899, -0.2914969834947889749, - 0.8921854600753849063, -0.0276323108621970258, -0.4257376659710629951, - -0.0938760381595044741, -0.7873218033841372643, 0.6012450975895150540, - 0.0938760381595044741, 0.7873218033841372643, -0.6012450975895150540, - -0.0986092863860908303, 0.1513605567468480073, 0.9692559984337008050, - 0.0986092863860908303, -0.1513605567468480073, -0.9692559984337008050, - -0.0189573629854957251, 0.9527983290277913797, 0.2944078167958268377, - 0.0189573629854957251, -0.9527983290277913797, -0.2944078167958268377, - 0.8394181189595459891, 0.3631767908642606346, 0.3398717995655929913, - 0.8703065201362156778, -0.4691145408161159214, 0.0770980453920554615, - 0.9141063746617547059, 0.1583184861345137973, -0.3535658252020681958, - 0.8348118627305495254, 0.3535663452183119837, 0.3271666140872500073, - 0.8541352373790773722, -0.4476738735312740247, 0.0569042988261160704, - 0.9034738474019414767, 0.1663655738425987851, -0.3227406124130587362, - 0.9861758757457432800, 0.0103496363116840455, 0.0635926656567585569, - 0.9643516568468981642, 0.0660181478622221818, -0.0304218028637989850 - ), 3, 26)) - - if( fuzz < max(abs(qbox26$loadings - tst ))) { - cat("Calculated value is not the same as test value in test Thurstone 10. Value:\n") - print(qbox26$loadings, digits=18) - cat("difference:\n") - print(qbox26$loadings - tst, digits=18) - all.ok <- FALSE - } - - - - tst <- t(matrix(c( - 0.9996572020207266096, 0.0216275672176080257, 0.0147555679097727491, - -0.0158190757965277796, 0.9480178905874908635, -0.3178235925273457108, - -0.0208622934749700742, 0.3174812237948764770, 0.9480350400953921897 - ), 3, 3)) - - if( fuzz < max(abs(qbox26$Th - tst ))) { - cat("Calculated value is not the same as test value in test Thurstone 11. Value:\n") - print(qbox26$Th, digits=18) - cat("difference:\n") - print(qbox26$Th - tst, digits=18) - all.ok <- FALSE - } - - -qminbox26 <- GPFoblq(box26, Tmat=diag(1,3), method="quartimin", eps=1e-5) - - tst <- t(matrix(c( - 0.6088436426802223966, -0.2567107018725688361, 0.7213648290819488773, - 0.7318447535507376367, 0.6298398026581654152, -0.0549983771960348838, - 0.7973321695017724364, -0.3855960314746548212, -0.4504478973568259437, - 0.8392144987741166906, 0.2994932968625432235, 0.4143558581243267924, - 0.8833452352200144020, -0.4361046712803113290, 0.1319331147095905710, - 0.9161366872228343672, 0.1535557844336666034, -0.3638337328539109072, - 0.7993355454002614158, 0.0571270784641514026, 0.5678963531379384033, - 0.8354288250614068101, 0.4626764152757318893, 0.1968789749765105790, - 0.8109923806202916641, -0.3989909333845649830, 0.3770226870580207779, - 0.9712737747877250305, -0.4740722765307348041, -0.0773243882106463137, - 0.8761501947960563808, 0.3456235893514668089, -0.2834183138879167174, - 0.9036601763684347643, -0.0290211959776035672, -0.4173652812159966974, - -0.0995525797764766768, -0.7788574612781464790, 0.6007791331268093060, - 0.0995525797764766768, 0.7788574612781464790, -0.6007791331268093060, - -0.1264036712449473909, 0.1653130238928011975, 0.9684661160120416890, - 0.1264036712449473909, -0.1653130238928011975, -0.9684661160120416890, - -0.0392946742598458687, 0.9571059478962877787, 0.2939285303852590125, - 0.0392946742598458687, -0.9571059478962877787, -0.2939285303852590125, - 0.8253744379910458173, 0.3729516010405902748, 0.3477554718030251846, - 0.8741734789142978634, -0.4631063486451737488, 0.0855349365396926159, - 0.9212130243051569467, 0.1581334796580046720, -0.3450412531516501846, - 0.8212340853954427367, 0.3631252613622908965, 0.3350076577679809153, - 0.8582635618771776720, -0.4420579024138228674, 0.0651757040961165046, - 0.9096561314838297330, 0.1665824736284239604, -0.3143133889989875307, - 0.9840845767693481294, 0.0168070160966761091, 0.0729425956763933708, - 0.9640420478016114014, 0.0709475796833391181, -0.0213192081807395371 - ), 3, 26)) - - if( fuzz < max(abs(qminbox26$loadings - tst ))) { - cat("Calculated value is not the same as test value in test Thurstone 12. Value:\n") - print(qminbox26$loadings, digits=18) - cat("difference:\n") - print(qminbox26$loadings - tst, digits=18) - all.ok <- FALSE - } - - - - tst <- t(matrix(c( - 1.000000000000000 , 0.00767934084449363279, 0.0170654511973979163, - 0.00767934084449363279, 1.000000000000000 , -0.0144994900961642244, - 0.01706545119739791630, -0.01449949009616422445, 1.000000000000000 - ), 3, 3)) - - if( fuzz < max(abs(qminbox26$Phi - tst ))) { - cat("Calculated value is not the same as test value in test Thurstone 13. Value:\n") - print(qminbox26$Phi, digits=18) - cat("difference:\n") - print(qminbox26$Phi - tst, digits=18) - all.ok <- FALSE - } - - - - tst <- t(matrix(c( - 0.9993401424148040668, 0.0347479564402226465, 0.0408645923859655008, - -0.0179660947915933414, 0.9476477730670300748, -0.3324117322929439067, - -0.0315673755054017430, 0.3174212937474846785, 0.9422486536594960604 - ), 3, 3)) - - if( fuzz < max(abs(qminbox26$Th - tst ))) { - cat("Calculated value is not the same as test value in test Thurstone 14. Value:\n") - print(qminbox26$Th, digits=18) - cat("difference:\n") - print(qminbox26$Th - tst, digits=18) - all.ok <- FALSE - } - - - -cat("tests completed.\n") - -if (! all.ok) stop("some tests FAILED") - - -cat("tests completed.\n") - -if (! all.ok) stop("some tests FAILED") - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/WansbeekMeijer.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/WansbeekMeijer.R deleted file mode 100644 index 26bab1e..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/WansbeekMeijer.R +++ /dev/null @@ -1,104 +0,0 @@ - Sys.getenv("R_LIBS") - library() - require("GPArotation") - search() - Sys.info() - - fuzz <- 1e-6 - all.ok <- TRUE - - data(WansbeekMeijer, package="GPArotation") - - fa.none <- factanal(factors=2, covmat=NetherlandsTV, rotation="none") - - tst <- t(matrix(c( - 0.6972803, -0.3736554, - 0.7774628, -0.3184149, - 0.6832300, -0.3620428, - 0.6612198, 0.2361132, - 0.6972393, 0.3026050, - 0.7100285, 0.4059509, - 0.6353584, 0.3526947 - ), 2, 7)) - - if( fuzz < max(abs(fa.none$loadings - tst))) { - cat("Calculated value is not the same as test value in test WansbeekMeijer 1. Value:\n") - print(fa.none$loadings, digits=18) - cat("difference:\n") - print(fa.none$loadings - tst, digits=18) - all.ok <- FALSE - } - - - - fa.varimax <- GPFoblq(fa.none$loadings, method="varimax", normalize=TRUE) - -# with eps=1e-8 -# tst <- t(matrix(c( -# 0.229695829694226694, -0.757005882905721683, -# 0.325474298411086493, -0.774533969509160203, -# 0.227951538606475851, -0.738861531224136225, -# 0.634850649690308022, -0.299876110481063607, -# 0.707312661165822032, -0.278246783076943283, -# 0.789359884149245072, -0.214120439603779994, -# 0.698885205896135120, -0.199081171877497243 -# ), 2, 7)) - -# with eps=1e-5 - tst <- t(matrix(c( - 0.229698038368303409, -0.757005212686898243, - 0.325476558225504142, -0.774533019824047542, - 0.227953694341768043, -0.738860866094951829, - 0.634851524619887475, -0.299874258087383661, - 0.707313472988376213, -0.278244719250824557, - 0.789360508873491518, -0.214118136377292989, - 0.698885786741510029, -0.199079132641678647 - ), 2, 7)) - - if( fuzz < max(abs(fa.varimax$loadings - tst))) { - cat("Calculated value is not the same as test value in test WansbeekMeijer 2. Value:\n") - print(fa.varimax$loadings, digits=18) - cat("difference:\n") - print(fa.varimax$loadings - tst, digits=18) - all.ok <- FALSE - } - - - - fa.oblimin <- GPFoblq(fa.none$loadings, method="oblimin", normalize=TRUE) - -# with eps=1e-8 -# tst <- t(matrix(c( -# -0.0244898894997362740, -0.8055076884898763057, -# 0.0821776433220552660, -0.7883517482514345032, -# -0.0194442483441249758, -0.7847120136813017233, -# 0.6350106056917923514, -0.1038114236654337219, -# 0.7293893902400611085, -0.0495156037400738894, -# 0.8517915457391848078, 0.0588983480418694277, -# 0.7504355940804637859, 0.0408946221245683056 -# ), 2, 7)) - -# with eps=1e-5 - tst <- t(matrix(c( - -0.0244886312423446446, -0.8055069385602275922, - 0.0821788889356081659, -0.7883509906546982693, - -0.0194430219824419312, -0.7847112821295906260, - 0.6350108529538124325, -0.1038111848933331444, - 0.7293895650539216069, -0.0495153948664520185, - 0.8517915670863017708, 0.0588984825074335624, - 0.7504356301074717184, 0.0408947509009953206 - ), 2, 7)) - - if( fuzz < max(abs(fa.oblimin$loadings - tst))) { - cat("Calculated value is not the same as test value in test WansbeekMeijer 3. Value:\n") - print(fa.oblimin$loadings, digits=18) - cat("difference:\n") - print(fa.oblimin$loadings - tst, digits=18) - all.ok <- FALSE - } - - -cat("tests completed.\n") - -if (! all.ok) stop("some tests FAILED") - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/rotations.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/rotations.R deleted file mode 100644 index b3b3e76..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/GPArotation/tests/rotations.R +++ /dev/null @@ -1,489 +0,0 @@ -# Tests here only compare against values computed previously with this code, -# to ensure there was no accidental change. It would be better to have -# comparisons with known correct values. - -# Test for oblimax is commented out as it appears to be unstable. - - - Sys.getenv("R_LIBS") - library() - require("GPArotation") - search() - Sys.info() - -require("stats") -require("GPArotation") - -fuzz <- 1e-6 -all.ok <- TRUE - - - data(ability.cov) - L <- loadings(factanal(factors = 2, covmat=ability.cov)) - - - if( 0.001 < max(abs(varimax(L, normalize=FALSE)$loadings - - Varimax(L, normalize=FALSE)$loadings))) { - cat("Calculated difference exceeds tolerance\n") - cat("difference:\n") - print(varimax(L, normalize=FALSE)$loadings - - Varimax(L, normalize=FALSE)$loadings, digits=18) - all.ok <- FALSE - } - - if( 0.01 < max(abs(varimax(L, normalize=TRUE)$loadings - - Varimax(L, normalize=TRUE, eps=1e-5)$loadings))) { - cat("Calculated difference exceeds tolerance\n") - cat("difference:\n") - print(varimax(L, normalize=TRUE)$loadings - - Varimax(L, normalize=TRUE, eps=1e-5)$loadings, digits=18) - all.ok <- FALSE - } - - - v <- oblimin(L, eps=1e-8)$loadings - tst <- t(matrix(c( - 0.3863615904740822504, 0.4745127741495974161, - -0.0110059418769087539, 0.6458720769633764514, - -0.0262926272350604423, 0.8961141105684561348, - -0.0180200526810754824, 0.4882928281695405048, - 0.9900944939102318543, -0.0370718282544326011, - 0.7905657274265397438, 0.0526109550054999417 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 1. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- quartimin(L, eps=1e-8)$loadings - tst <- t(matrix(c( - 0.3863615904740822504, 0.4745127741495974161, - -0.0110059418769087539, 0.6458720769633764514, - -0.0262926272350604423, 0.8961141105684561348, - -0.0180200526810754824, 0.4882928281695405048, - 0.9900944939102318543, -0.0370718282544326011, - 0.7905657274265397438, 0.0526109550054999417 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 2. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- targetT(L, Target=matrix(c(rep(1,3),rep(0,6),rep(1,3)), 6,2), - eps=1e-5)$loadings - tst <- t(matrix(c( - 0.551529228817982942, 0.4905002767031292898, - 0.217748645523411000, 0.6027046291262584399, - 0.291173432863349457, 0.8348885228488550636, - 0.154994397662456290, 0.4544843569140373241, - 0.969702339393929247, 0.0850652965070581996, - 0.803390575440818822, 0.1448091121037717866 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 3. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- targetQ(L, Target=matrix(c(rep(1,3),rep(0,6),rep(1,3)), 6,2), - eps=1e-5)$loadings - tst <- t(matrix(c( - 0.735795682866631218, 0.565351705145453853, - 0.433590223819374398, 0.664644550038417159, - 0.589924557708411568, 0.920006940799857786, - 0.317543426981046928, 0.500590650032113116, - 1.021758247914384077, 0.155121528590726393, - 0.872521244896209747, 0.208735706420634437 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 4. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - # Does not converge even with maxit=10000, but the loadings matrix is not - # changing. Possibly the gradient is extremely large even very close to opt. - v <- pstT(L, W = matrix(c(rep(.4,6),rep(.6,6)), 6,2), - Target= matrix(c(rep(1,3),rep(0,6),rep(1,3)), 6,2), - maxit=1000, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.37067889993474656407, 0.638257130653133720, - 0.01855112570739854416, 0.640564749523800270, - 0.01576132191496706567, 0.884065831441111172, - 0.00524531003824213384, 0.480158078874985073, - 0.89458633399812259590, 0.383762977265515448, - 0.71793428958051475064, 0.388556883222951677 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 5. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - # Does not converge even with maxit=10000, but the loadings matrix is not - # changing. Possibly the gradient is extremely large even very close to opt. - v <- pstQ(L, W = matrix(c(rep(.4,6),rep(.6,6)), 6,2), - Target= matrix(c(rep(1,3),rep(0,6),rep(1,3)), 6,2), - maxit=1000, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.573125161748393785, 0.700868331877288475, - 0.214899397066479453, 0.681727425525818886, - 0.286558275327103040, 0.940272379393286339, - 0.152257795885557295, 0.510481967637567036, - 1.029289798076480578, 0.462598702071116141, - 0.850691132520651205, 0.456859727346562328 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 6. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - -# oblimax -# this is test value on one computer -# tst <- t(matrix(c( -# -8111059.94622692652, 8111060.62253121007, -# 1495036.43465861562, -1495035.79614594672, -# 2331634.63904705830, -2331633.75893370388, -# 1356735.91680212389, -1356735.43916810025, -# -23187491.19758165255, 23187491.68068471923, -# -18357040.58573083207, 18357041.05348757654 -# ), 2, 6)) -# -# this is test value on another computer -# tst <- t(matrix(c( -# 2694770.06630349346, -2694769.38999920478, -# -496701.45733913727, 496702.09585180727, -# -774647.63529061736, 774648.51540397422, -# -450753.43529273639, 450753.91292676108, -# 7703672.48495316971, -7703672.00185009185, -# 6098832.71036116872, -6098832.24260441773 -# ), 2, 6)) -# -# this does not converge on all platforms and has large differences possible a mistake ??? -# v <- oblimax(L, eps=1e-5)$loadings -# if( fuzz < max(abs(v - tst))) { -# cat("Calculated value is not the same as test value in test rotations 7. Value:\n") -# print(v, digits=18) -# cat("difference:\n") -# print(v - tst, digits=18) -# all.ok <- FALSE -# } - - - v <- entropy(L, maxit=3000, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.528292107548243184, 0.515443945340967824, - 0.189686511729033253, 0.612116304198454975, - 0.252311894464850861, 0.847442931117894815, - 0.133843268148035738, 0.461156452364903380, - 0.964740133927989407, 0.129750551769587635, - 0.795847094000000532, 0.181751199795689433 - ), 2, 6)) - - if( 0.01 < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 8. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- quartimax(L, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.534714740804540178, 0.508778102568043678, - 0.197348140750149392, 0.609689309353509956, - 0.262919828098457153, 0.844212045390758559, - 0.139616102327241837, 0.459441658926639795, - 0.966291466215733252, 0.117641548844535412, - 0.798063848020893585, 0.171756193883937508 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 9. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- Varimax(L, eps=1e-8)$loadings - tst <- t(matrix(c( - 0.515866523962843160, 0.527879475961036904, - 0.175054634278874244, 0.616460231981747930, - 0.232057748479543163, 0.853211588623112749, - 0.122822468397975171, 0.464213243286899446, - 0.961376376417989453, 0.152689863976982837, - 0.791292800869773050, 0.200653429940987366 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 10. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- simplimax(L, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.3384175759313114429, 0.508414890494446547464, - -0.0654601124161610648, 0.670992229004664153535, - -0.1016231721735353366, 0.930535379393095940515, - -0.0589933707274080121, 0.506904360351960181497, - 0.9733094402675376289, 0.000234046050254643859, - 0.7702037184085044341, 0.085651123319384916965 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 11. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- bentlerT(L, eps=1e-8)$loadings - tst <- t(matrix(c( - 0.523583611303327312, 0.520226117818945788, - 0.184113022124463677, 0.613815719643687197, - 0.244596116053327067, 0.849702038129718673, - 0.129644684715025493, 0.462354355134084738, - 0.963520501269179652, 0.138517057902201340, - 0.794161628656258278, 0.188979901644201559 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 12. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- bentlerQ(L, eps=1e-8)$loadings - tst <- t(matrix(c( - 0.3801726240258240241, 0.4741208368044214638, - -0.0223632969057368826, 0.6514196922540864687, - -0.0421105927111659756, 0.9039359851665277334, - -0.0266594447192576613, 0.4925968005718689424, - 0.9961524457620027917, -0.0485973498906049697, - 0.7939648477384558811, 0.0440983921679098251 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 13. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- tandemI(L, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.615424480780047745, 0.4074649925368262759, - 0.300894306348887419, 0.5658002819054848143, - 0.406455233467338028, 0.7852483408305571677, - 0.217785179074990981, 0.4279590047675180808, - 0.971977129465111611, -0.0530960591067626969, - 0.815800376450207976, 0.0295946184147908228 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 14. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - - v <- tandemII(L, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.512160139332842212, 0.531476249107136312, - 0.170736763115044710, 0.617670057812827134, - 0.226081850628144149, 0.854814488884392154, - 0.119571200821562001, 0.465061309851099225, - 0.960284416460420398, 0.159413208985883820, - 0.789869387186175276, 0.206185467095899383 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 15. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- geominT(L, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.572197044101002361, 0.4662247895688098054, - 0.243573415560656120, 0.5927388411683653935, - 0.326956608263186954, 0.8215352639437966120, - 0.174476792179181994, 0.4473668997335142894, - 0.972471249855535680, 0.0431091626026945812, - 0.808894688433769660, 0.1099794466209375043 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 16. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- geominQ(L, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.39672053553904490508, 0.4713295988080449250, - 0.00424452688463150020, 0.6389466007374070555, - -0.00510976786312981532, 0.8864521406378518265, - -0.00646959173137159373, 0.4830101828530461994, - 0.98709860078485589518, -0.0318959930081098297, - 0.79011178369962709045, 0.0558689642678330683 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 17. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- cfT(L, eps=1e-8)$loadings - tst <- t(matrix(c( - 0.534721263659975854, 0.508771247100584523, - 0.197355957387199576, 0.609686779159006154, - 0.262930651479430233, 0.844208674501022327, - 0.139621992686633722, 0.459439868910532512, - 0.966292974385164483, 0.117629160286744874, - 0.798066049992627313, 0.171745962120156664 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 18. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- cfQ(L, eps=1e-8)$loadings - tst <- t(matrix(c( - 0.3863615904740822504, 0.4745127741495974161, - -0.0110059418769087539, 0.6458720769633764514, - -0.0262926272350604423, 0.8961141105684561348, - -0.0180200526810754824, 0.4882928281695405048, - 0.9900944939102318543, -0.0370718282544326011, - 0.7905657274265397438, 0.0526109550054999417 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 19. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- infomaxT(L, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.495330443338021176, 0.547195361446864537, - 0.151384273205308784, 0.622695868320644275, - 0.199304253086364791, 0.861451466010626055, - 0.105004533733904976, 0.468565194910632365, - 0.954843809781045660, 0.189293503899924942, - 0.783052579543945471, 0.230726576980168713 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 20. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- infomaxQ(L, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.39327554287862442894, 0.4693137508305071925, - -0.00319802321222481794, 0.6422985517185823001, - -0.01549245038490981718, 0.8912279460026399924, - -0.01214605901641467763, 0.4856544522916727002, - 0.99260028929193111491, -0.0433225495465055510, - 0.79356458059567791530, 0.0471559021503157039 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 21. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - v <- mccammon(L, eps=1e-5)$loadings - tst <- t(matrix(c( - 0.4293472299617892007, 0.600363196582340275, - 0.0790140496845253004, 0.635943490060206229, - 0.0992523811009183854, 0.878618107277518656, - 0.0506062164774049028, 0.477512622702450096, - 0.9268544198491108776, 0.297488850382792269, - 0.7514463663627769519, 0.318958389348199534 - ), 2, 6)) - - if( fuzz < max(abs(v - tst))) { - cat("Calculated value is not the same as test value in test rotations 22. Value:\n") - print(v, digits=18) - cat("difference:\n") - print(v - tst, digits=18) - all.ok <- FALSE - } - - - -cat("tests completed.\n") - - -if (! all.ok) stop("some tests FAILED") diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/DESCRIPTION b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/DESCRIPTION deleted file mode 100644 index 38d8f24..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/DESCRIPTION +++ /dev/null @@ -1,29 +0,0 @@ -Package: R6 -Title: Classes with Reference Semantics -Version: 2.2.2 -Authors@R: person("Winston", "Chang", role = c("aut", "cre"), email = - "winston@stdout.org") -Description: The R6 package allows the creation of classes with - reference semantics, similar to R's built-in reference classes. - Compared to reference classes, R6 classes are simpler and - lighter-weight, and they are not built on S4 classes so they do not - require the methods package. These classes allow public and private - members, and they support inheritance, even when the classes are - defined in different packages. -Depends: R (>= 3.0) -Suggests: knitr, microbenchmark, pryr, testthat, ggplot2, scales -License: MIT + file LICENSE -URL: https://github.com/wch/R6/ -LazyData: true -VignetteBuilder: knitr -RoxygenNote: 6.0.1 -NeedsCompilation: no -Packaged: 2017-06-12 18:48:43 UTC; winston -Author: Winston Chang [aut, cre] -Maintainer: Winston Chang -Repository: CRAN -Date/Publication: 2017-06-17 08:22:59 UTC -Built: R 3.4.1; ; 2017-09-09 18:18:18 UTC; unix -InstallAgent: packrat 0.4.8.38 -InstallSource: CRAN -Hash: b2366cd9d2f3851a5704b4e192b985c2 diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/INDEX b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/INDEX deleted file mode 100644 index 2699e80..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/INDEX +++ /dev/null @@ -1,3 +0,0 @@ -R6Class Create an R6 reference object generator -as.list.R6 Create a list from an R6 object -is.R6 Is an object an R6 Class Generator or Object? diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/LICENSE b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/LICENSE deleted file mode 100644 index 9b8dd6a..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/LICENSE +++ /dev/null @@ -1,2 +0,0 @@ -YEAR: 2015 -COPYRIGHT HOLDER: RStudio diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/Rd.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/Rd.rds deleted file mode 100644 index e698501..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/Rd.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/features.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/features.rds deleted file mode 100644 index 2027d3f..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/features.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/hsearch.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/hsearch.rds deleted file mode 100644 index 09c3899..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/hsearch.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/links.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/links.rds deleted file mode 100644 index ed9dfd7..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/links.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/nsInfo.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/nsInfo.rds deleted file mode 100644 index 521aa35..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/nsInfo.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/package.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/package.rds deleted file mode 100644 index 72ea9de..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/package.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/vignette.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/vignette.rds deleted file mode 100644 index 404b9d9..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/Meta/vignette.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/NAMESPACE b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/NAMESPACE deleted file mode 100644 index b252431..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/NAMESPACE +++ /dev/null @@ -1,11 +0,0 @@ -# Generated by roxygen2: do not edit by hand - -S3method(as.list,R6) -S3method(format,R6) -S3method(format,R6ClassGenerator) -S3method(plot,R6) -S3method(print,R6) -S3method(print,R6ClassGenerator) -export(R6Class) -export(is.R6) -export(is.R6Class) diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/NEWS.md b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/NEWS.md deleted file mode 100644 index 8baa479..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/NEWS.md +++ /dev/null @@ -1,101 +0,0 @@ -R6 2.2.2 -======== - -* Fixed [#108](https://github.com/wch/R6/issues/108): When an object with a `super` object and an active binding in the `super` object was cloned, the new object's `super` object did not get the active binding -- it was a normal function. - -* Fixed [#119](https://github.com/wch/R6/issues/119): When a class had two levels of inheritance, an instance of that class's `super` object could contain methods that had an incorrect enclosing environment. - - -R6 2.2.1 -======== - -* Vignettes now only try use the microbenchmark package if it is present. This is so that the package builds properly on platforms where microbenchmark is not present, like Solaris. - -* Fixed ending position for `trim()`. - -R6 2.2.0 -======== - -* Classes can define finalizers explicitly, by defining a public `finalize` method. ([#92](https://github.com/wch/R6/issues/92), [#93](https://github.com/wch/R6/pull/93)) - -* Added function `is.R6()` and `is.R6Class()`. ([#95](https://github.com/wch/R6/pull/95)) - -* Fixed [#96](https://github.com/wch/R6/issues/96): R6 now avoids using `$` and `[[` after the class has been assigned to the object. This allows the user to provide their own methods for `$` and `[[` without causing problems to R6's operation. - -R6 2.1.3 -======== - -* The `plot` S3 method for R6 objects will call `$plot` on the object if present. (#77) - -* Fixed printing of members that are R6 objects. (#88) - -* Fixed deep cloning for non-portable classes. (#85) - -* Added `as.list.R6` method. (#91) - -R6 2.1.2 -======== - -* Implemented `format.R6()` and `format.R6ClassGenerator`, the former calls a public `format` method if defined. This might change the functionality of existing classes that define a public `format` method intended for other purposes (#73. Thanks to Kirill Müller) - -* Functions are shown with their interface in `print` and `format`, limited to one line (#76. Thanks to Kirill Müller) - -* R6 objects and generators print out which class they inherit from. (#67) - -R6 2.1.1 -======== - -* Fixed a bug with printing R6 objects when a `[[` method is defined for the class. (#70) - -* Fixed cloning of objects that call a `super` method which accesses `private`. (#72) - -R6 2.1.0 -======== - -* Added support for making clones of R6 objects with a `clone()` method on R6 objects. The `deep=TRUE` option allows for making clones that have copies of fields with reference semantics (like other R6 objects). (#27) - -* Allow adding public or private members when there were no public or private members to begin with. (#51) - -* Previously, when an R6 object was printed, it accessed (and called) active bindings. Now it simply reports that a field is an active binding. (#37, #38. Thanks to Oscar de Lama) - -* Printing private members now works correctly for portable R6 objects. (#26) - -* The 'lock' argument has been renamed to 'lock_objects'. Also, there is a new argument, 'lock_class', which can prevent changes to the class. (#52) - -* Fixed printing of NULL fields. - -R6 2.0.1 -======== - -* A superclass is validated on object instantation, not on class creation. - -* Added `debug` and `undebug` methods to generator object. - -R6 2.0 -======== - -* [BREAKING CHANGE] Added `portable` option, which allows inheritance across different package namespaces, and made it the default. - -* Added `set()` method on class generator object, so new fields and methods can be added after the generator has been created. - -* All of the functions involved in instantiating objects are encapsulated in an environment separate from the R6 namespace. This means that if a generator is created with one version of R6, saved, then restored in a new R session that has a different version of R6, there shouldn't be any problems with compatibility. - -* Methods are locked so that they can't be changed. (Fixes #19) - -* Inheritance of superclasses is dynamic; instead of reading in the superclass when a class is created, this happens each time an object is instantiated. (Fixes #12) - -* Added trailing newline when printing R6 objects. (Thanks to Gabor Csardi) - -* The `print` method of R6 objects can be redefined. (Thanks to Gabor Csardi) - -R6 1.0.1 -======== - -* First release on CRAN. - -* Removed pryr from suggested packages. - -R6 1.0 -======== - -* First release diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/R/R6 b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/R/R6 deleted file mode 100644 index 3b65e3c..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/R/R6 +++ /dev/null @@ -1,27 +0,0 @@ -# File share/R/nspackloader.R -# Part of the R package, http://www.R-project.org -# -# Copyright (C) 1995-2012 The R Core Team -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# A copy of the GNU General Public License is available at -# http://www.r-project.org/Licenses/ - -local({ - info <- loadingNamespaceInfo() - pkg <- info$pkgname - ns <- .getNamespace(as.name(pkg)) - if (is.null(ns)) - stop("cannot find namespace environment for ", pkg, domain = NA); - dbbase <- file.path(info$libname, pkg, "R", pkg) - lazyLoad(dbbase, ns, filter = function(n) n != ".__NAMESPACE__.") -}) diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/R/R6.rdb b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/R/R6.rdb deleted file mode 100644 index c77c0b0..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/R/R6.rdb and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/R/R6.rdx b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/R/R6.rdx deleted file mode 100644 index 1f281bd..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/R/R6.rdx and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Debugging.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Debugging.R deleted file mode 100644 index 1071897..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Debugging.R +++ /dev/null @@ -1,39 +0,0 @@ -## ----echo = FALSE-------------------------------------------------------- -knitr::opts_chunk$set(collapse = TRUE, comment = "#>") - -## ----eval=FALSE---------------------------------------------------------- -# # An example class -# Simple <- R6Class("Simple", -# public = list( -# x = 10, -# getx = function() self$x -# ) -# ) -# -# # This will enable debugging the getx() method for objects of the 'Simple' -# # class that are instantiated in the future. -# Simple$debug("getx") -# -# s <- Simple$new() -# s$getx() -# # [Debugging prompt] - -## ----eval=FALSE---------------------------------------------------------- -# # Disable debugging for future instances: -# Simple$undebug("getx") -# -# s <- Simple$new() -# s$getx() -# #> [1] 10 - -## ----eval=FALSE---------------------------------------------------------- -# s <- Simple$new() -# debug(s$getx) -# s$getx() -# # [Debugging prompt] - -## ----eval=FALSE---------------------------------------------------------- -# undebug(s$getx) -# s$getx() -# #> [1] 10 - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Debugging.Rmd b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Debugging.Rmd deleted file mode 100644 index a57e6de..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Debugging.Rmd +++ /dev/null @@ -1,76 +0,0 @@ ---- -title: "Debugging methods in R6 objects" -output: - html_document: - theme: null - css: mystyle.css - toc: yes -vignette: > - %\VignetteEngine{knitr::rmarkdown} - %\VignetteIndexEntry{Debugging methods in R6 objects} - %\usepackage[utf8]{inputenc} ---- - -```{r echo = FALSE} -knitr::opts_chunk$set(collapse = TRUE, comment = "#>") -``` - -Debugging methods in R6 classes is somewhat different from debugging normal R functions. - -RStudio breakpoints don't work in R6 class methods. The simplest way to debug code is to insert a `browser()` line where you want to open a debugging console, reload the classes, and then step through your code. But this involves modifying your code, reloading it, and re-instantiating any objects you want to test. - -## Enabling debugging for all future instances of a class - -R6 generator objects have a method called `debug()` which will enable debugging for a method. This will affect all instances of the class that are created after the `debug()` is called. - -```{r eval=FALSE} -# An example class -Simple <- R6Class("Simple", - public = list( - x = 10, - getx = function() self$x - ) -) - -# This will enable debugging the getx() method for objects of the 'Simple' -# class that are instantiated in the future. -Simple$debug("getx") - -s <- Simple$new() -s$getx() -# [Debugging prompt] -``` - -To disable debugging for future instances, use the generator's `undebug()` method: - -```{r eval=FALSE} -# Disable debugging for future instances: -Simple$undebug("getx") - -s <- Simple$new() -s$getx() -#> [1] 10 -``` - - -## Debugging methods in individual objects - -To enable debugging for a method in a single instance of an object, use the `debug()` function (not the `debug()` method in the generator object). - -```{r eval=FALSE} -s <- Simple$new() -debug(s$getx) -s$getx() -# [Debugging prompt] -``` - -Use `undebug()` to disable debugging on an object's method. - -```{r eval=FALSE} -undebug(s$getx) -s$getx() -#> [1] 10 -``` - - -You can also use the `trace()` function to specify where in a method you want to drop into the debugging console. diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Debugging.html b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Debugging.html deleted file mode 100644 index f6d0237..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Debugging.html +++ /dev/null @@ -1,106 +0,0 @@ - - - - - - - - - - - - - - -Debugging methods in R6 objects - - - - - - - - - - - - - - - - - - - -

Debugging methods in R6 objects

- - - - -

Debugging methods in R6 classes is somewhat different from debugging normal R functions.

-

RStudio breakpoints don’t work in R6 class methods. The simplest way to debug code is to insert a browser() line where you want to open a debugging console, reload the classes, and then step through your code. But this involves modifying your code, reloading it, and re-instantiating any objects you want to test.

-
-

Enabling debugging for all future instances of a class

-

R6 generator objects have a method called debug() which will enable debugging for a method. This will affect all instances of the class that are created after the debug() is called.

-
# An example class
-Simple <- R6Class("Simple",
-  public = list(
-    x = 10,
-    getx = function() self$x
-  )
-)
-
-# This will enable debugging the getx() method for objects of the 'Simple'
-# class that are instantiated in the future.
-Simple$debug("getx")
-
-s <- Simple$new()
-s$getx()
-# [Debugging prompt]
-

To disable debugging for future instances, use the generator’s undebug() method:

-
# Disable debugging for future instances:
-Simple$undebug("getx")
-
-s <- Simple$new()
-s$getx()
-#> [1] 10
-
-
-

Debugging methods in individual objects

-

To enable debugging for a method in a single instance of an object, use the debug() function (not the debug() method in the generator object).

-
s <- Simple$new()
-debug(s$getx)
-s$getx()
-# [Debugging prompt]
-

Use undebug() to disable debugging on an object’s method.

-
undebug(s$getx)
-s$getx()
-#> [1] 10
-

You can also use the trace() function to specify where in a method you want to drop into the debugging console.

-
- - - - - - - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Introduction.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Introduction.R deleted file mode 100644 index 215ea0f..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Introduction.R +++ /dev/null @@ -1,432 +0,0 @@ -## ----echo = FALSE-------------------------------------------------------- -library(pryr) -knitr::opts_chunk$set(collapse = TRUE, comment = "#>") - -## ------------------------------------------------------------------------ -library(R6) - -Person <- R6Class("Person", - public = list( - name = NULL, - hair = NULL, - initialize = function(name = NA, hair = NA) { - self$name <- name - self$hair <- hair - self$greet() - }, - set_hair = function(val) { - self$hair <- val - }, - greet = function() { - cat(paste0("Hello, my name is ", self$name, ".\n")) - } - ) -) - -## ------------------------------------------------------------------------ -ann <- Person$new("Ann", "black") -ann - -## ------------------------------------------------------------------------ -ann$hair -ann$greet() -ann$set_hair("red") -ann$hair - -## ------------------------------------------------------------------------ -Queue <- R6Class("Queue", - public = list( - initialize = function(...) { - for (item in list(...)) { - self$add(item) - } - }, - add = function(x) { - private$queue <- c(private$queue, list(x)) - invisible(self) - }, - remove = function() { - if (private$length() == 0) return(NULL) - # Can use private$queue for explicit access - head <- private$queue[[1]] - private$queue <- private$queue[-1] - head - } - ), - private = list( - queue = list(), - length = function() base::length(private$queue) - ) -) - -q <- Queue$new(5, 6, "foo") - -## ------------------------------------------------------------------------ -# Add and remove items -q$add("something") -q$add("another thing") -q$add(17) -q$remove() -q$remove() - -## ----eval = FALSE-------------------------------------------------------- -# q$queue -# #> NULL -# q$length() -# #> Error: attempt to apply non-function - -## ------------------------------------------------------------------------ -q$add(10)$add(11)$add(12) - -## ------------------------------------------------------------------------ -q$remove() -q$remove() -q$remove() -q$remove() - -## ------------------------------------------------------------------------ -Numbers <- R6Class("Numbers", - public = list( - x = 100 - ), - active = list( - x2 = function(value) { - if (missing(value)) return(self$x * 2) - else self$x <- value/2 - }, - rand = function() rnorm(1) - ) -) - -n <- Numbers$new() -n$x - -## ------------------------------------------------------------------------ -n$x2 - -## ------------------------------------------------------------------------ -n$x2 <- 1000 -n$x - -## ----eval=FALSE---------------------------------------------------------- -# n$rand -# #> [1] 0.2648 -# n$rand -# #> [1] 2.171 -# n$rand <- 3 -# #> Error: unused argument (quote(3)) - -## ------------------------------------------------------------------------ -# Note that this isn't very efficient - it's just for illustrating inheritance. -HistoryQueue <- R6Class("HistoryQueue", - inherit = Queue, - public = list( - show = function() { - cat("Next item is at index", private$head_idx + 1, "\n") - for (i in seq_along(private$queue)) { - cat(i, ": ", private$queue[[i]], "\n", sep = "") - } - }, - remove = function() { - if (private$length() - private$head_idx == 0) return(NULL) - private$head_idx <<- private$head_idx + 1 - private$queue[[private$head_idx]] - } - ), - private = list( - head_idx = 0 - ) -) - -hq <- HistoryQueue$new(5, 6, "foo") -hq$show() -hq$remove() -hq$show() -hq$remove() - -## ------------------------------------------------------------------------ -CountingQueue <- R6Class("CountingQueue", - inherit = Queue, - public = list( - add = function(x) { - private$total <<- private$total + 1 - super$add(x) - }, - get_total = function() private$total - ), - private = list( - total = 0 - ) -) - -cq <- CountingQueue$new("x", "y") -cq$get_total() -cq$add("z") -cq$remove() -cq$remove() -cq$get_total() - -## ------------------------------------------------------------------------ -SimpleClass <- R6Class("SimpleClass", - public = list(x = NULL) -) - -SharedField <- R6Class("SharedField", - public = list( - e = SimpleClass$new() - ) -) - -s1 <- SharedField$new() -s1$e$x <- 1 - -s2 <- SharedField$new() -s2$e$x <- 2 - -# Changing s2$e$x has changed the value of s1$e$x -s1$e$x - -## ------------------------------------------------------------------------ -NonSharedField <- R6Class("NonSharedField", - public = list( - e = NULL, - initialize = function() self$e <- SimpleClass$new() - ) -) - -n1 <- NonSharedField$new() -n1$e$x <- 1 - -n2 <- NonSharedField$new() -n2$e$x <- 2 - -# n2$e$x does not affect n1$e$x -n1$e$x - -## ------------------------------------------------------------------------ -RC <- setRefClass("RC", - fields = list(x = 'ANY'), - methods = list( - getx = function() x, - setx = function(value) x <<- value - ) -) - -rc <- RC$new() -rc$setx(10) -rc$getx() - -## ------------------------------------------------------------------------ -NP <- R6Class("NP", - portable = FALSE, - public = list( - x = NA, - getx = function() x, - setx = function(value) x <<- value - ) -) - -np <- NP$new() -np$setx(10) -np$getx() - -## ------------------------------------------------------------------------ -P <- R6Class("P", - portable = TRUE, # This is default - public = list( - x = NA, - getx = function() self$x, - setx = function(value) self$x <- value - ) -) - -p <- P$new() -p$setx(10) -p$getx() - -## ------------------------------------------------------------------------ -Simple <- R6Class("Simple", - public = list( - x = 1, - getx = function() self$x - ) -) - -Simple$set("public", "getx2", function() self$x*2) - -# To replace an existing member, use overwrite=TRUE -Simple$set("public", "x", 10, overwrite = TRUE) - -s <- Simple$new() -s$x -s$getx2() - -## ------------------------------------------------------------------------ -# Create a locked class -Simple <- R6Class("Simple", - public = list( - x = 1, - getx = function() self$x - ), - lock_class = TRUE -) - -# This would result in an error -# Simple$set("public", "y", 2) - -# Unlock the class -Simple$unlock() - -# Now it works -Simple$set("public", "y", 2) - -# Lock the class again -Simple$lock() - -## ------------------------------------------------------------------------ -Simple <- R6Class("Simple", - public = list( - x = 1, - getx = function() self$x - ) -) - -s <- Simple$new() - -# Create a clone -s1 <- s$clone() -# Modify it -s1$x <- 2 -s1$getx() - -# Original is unaffected by changes to the clone -s$getx() - -## ----clone-size, echo=FALSE---------------------------------------------- -# Calculate size of clone method in this block. -Cloneable <- R6Class("Cloneable", cloneable = TRUE) -NonCloneable <- R6Class("NonCloneable", cloneable = FALSE) - -c1 <- Cloneable$new() -c2 <- Cloneable$new() -# Bytes for each new cloneable object -cloneable_delta <- object_size(c1, c2) - object_size(c2) - -nc1 <- NonCloneable$new() -nc2 <- NonCloneable$new() -# Bytes for each new noncloneable object -noncloneable_delta <- object_size(nc1, nc2) - object_size(nc2) - -# Number of bytes used by each copy of clone method -additional_clone_method_bytes <- cloneable_delta - noncloneable_delta -additional_clone_method_bytes_str <- capture.output(print(additional_clone_method_bytes)) - -# Number of bytes used by first copy of a clone method -first_clone_method_bytes <- object_size(c1) - object_size(nc1) -# Need some trickery to get the nice output from pryr::print.bytes -first_clone_method_bytes_str <- capture.output(print(first_clone_method_bytes)) - -## ------------------------------------------------------------------------ -Simple <- R6Class("Simple", public = list(x = 1)) - -Cloneable <- R6Class("Cloneable", - public = list( - s = NULL, - initialize = function() self$s <- Simple$new() - ) -) - -c1 <- Cloneable$new() -c2 <- c1$clone() - -# Change c1's `s` field -c1$s$x <- 2 - -# c2's `s` is the same object, so it reflects the change -c2$s$x - -## ------------------------------------------------------------------------ -c3 <- c1$clone(deep = TRUE) - -# Change c1's `s` field -c1$s$x <- 3 - -# c2's `s` is different -c3$s$x - -## ------------------------------------------------------------------------ -CloneEnv <- R6Class("CloneEnv", - public = list( - a = NULL, - b = NULL, - v = 1, - initialize = function() { - self$a <- new.env(parent = emptyenv()) - self$b <- new.env(parent = emptyenv()) - self$a$x <- 1 - self$b$x <- 1 - } - ), - private = list( - deep_clone = function(name, value) { - # With x$clone(deep=TRUE) is called, the deep_clone gets invoked once for - # each field, with the name and value. - if (name == "a") { - # `a` is an environment, so use this quick way of copying - list2env(as.list.environment(value, all.names = TRUE), - parent = emptyenv()) - } else { - # For all other fields, just return the value - value - } - } - ) -) - -c1 <- CloneEnv$new() -c2 <- c1$clone(deep = TRUE) - -## ------------------------------------------------------------------------ -# Modifying c1$a doesn't affect c2$a, because they're separate objects -c1$a$x <- 2 -c2$a$x - -# Modifying c1$b does affect c2$b, because they're the same object -c1$b$x <- 3 -c2$b$x - -# Modifying c1$v doesn't affect c2$v, because they're not reference objects -c1$v <- 4 -c2$v - -## ------------------------------------------------------------------------ -PrettyCountingQueue <- R6Class("PrettyCountingQueue", - inherit = CountingQueue, - public = list( - print = function(...) { - cat(" of ", self$get_total(), " elements\n", sep = "") - invisible(self) - } - ) -) - -## ------------------------------------------------------------------------ -pq <- PrettyCountingQueue$new(1, 2, "foobar") -pq - -## ------------------------------------------------------------------------ -A <- R6Class("A", public = list( - finalize = function() { - print("Finalizer has been called!") - } -)) - - -# Instantiate an object: -obj <- A$new() - -# Remove the single existing reference to it, and force garbage collection -# (normally garbage collection will happen automatically from time -# to time) -rm(obj); gc() - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Introduction.Rmd b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Introduction.Rmd deleted file mode 100644 index 136844b..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Introduction.Rmd +++ /dev/null @@ -1,624 +0,0 @@ ---- -title: "Introduction to R6 classes" -output: - html_document: - theme: null - css: mystyle.css - toc: yes -vignette: > - %\VignetteEngine{knitr::rmarkdown} - %\VignetteIndexEntry{Introduction to R6 classes} - %\usepackage[utf8]{inputenc} ---- - -```{r echo = FALSE} -library(pryr) -knitr::opts_chunk$set(collapse = TRUE, comment = "#>") -``` - -The R6 package provides a type of class which is similar to R's standard reference classes, but it is more efficient and doesn't depend on S4 classes and the methods package. - -## R6 classes - -R6 classes are similar to R's standard reference classes, but are lighter weight, and avoid some issues that come along with using S4 classes (R's reference classes are based on S4). For more information about speed and memory footprint, see the Performance vignette. - -Unlike many objects in R, instances (objects) of R6 classes have reference semantics. R6 classes also support: - -* public and private methods -* active bindings -* inheritance (superclasses) which works across packages - -Why the name R6? When R's reference classes were introduced, some users, following the names of R's existing class systems S3 and S4, called the new class system R5 in jest. Although reference classes are not actually called R5, the name of this package and its classes takes inspiration from that name. - -The name R5 was also a code-name used for a different object system started by Simon Urbanek, meant to solve some issues with S4 relating to syntax and performance. However, the R5 branch was shelved after a little development, and it was never released. - - -### Basics - -Here's how to create a simple R6 class. The `public` argument is a list of items, which can be functions and fields (non-functions). Functions will be used as methods. - -```{r} -library(R6) - -Person <- R6Class("Person", - public = list( - name = NULL, - hair = NULL, - initialize = function(name = NA, hair = NA) { - self$name <- name - self$hair <- hair - self$greet() - }, - set_hair = function(val) { - self$hair <- val - }, - greet = function() { - cat(paste0("Hello, my name is ", self$name, ".\n")) - } - ) -) -``` - -To instantiate an object of this class, use `$new()`: - -```{r} -ann <- Person$new("Ann", "black") -ann -``` - -The `$new()` method creates the object and calls the `initialize()` method, if it exists. - -Inside methods of the class, `self` refers to the object. Public members of the object (all you've seen so far) are accessed with `self$x`, and assignment is done with `self$x <- y`. Note that by default, `self` is required to access members, although for non-portable classes which we'll see later, it is optional. - -Once the object is instantiated, you can access values and methods with `$`: - -```{r} -ann$hair -ann$greet() -ann$set_hair("red") -ann$hair -``` - -Implementation note: The external face of an R6 object is basically an environment with the public members in it. This is also known as the *public environment*. An R6 object's methods have a separate *enclosing environment* which, roughly speaking, is the environment they "run in". This is where `self` binding is found, and it is simply a reference back to public environment. - -### Private members - -In the previous example, all the members were public. It's also possible to add private members: - -```{r} -Queue <- R6Class("Queue", - public = list( - initialize = function(...) { - for (item in list(...)) { - self$add(item) - } - }, - add = function(x) { - private$queue <- c(private$queue, list(x)) - invisible(self) - }, - remove = function() { - if (private$length() == 0) return(NULL) - # Can use private$queue for explicit access - head <- private$queue[[1]] - private$queue <- private$queue[-1] - head - } - ), - private = list( - queue = list(), - length = function() base::length(private$queue) - ) -) - -q <- Queue$new(5, 6, "foo") -``` - -Whereas public members are accessed with `self`, like `self$add()`, private members are accessed with `private`, like `private$queue`. - -The public members can be accessed as usual: - -```{r} -# Add and remove items -q$add("something") -q$add("another thing") -q$add(17) -q$remove() -q$remove() -``` - -However, private members can't be accessed directly: - -```{r eval = FALSE} -q$queue -#> NULL -q$length() -#> Error: attempt to apply non-function -``` - -A useful design pattern is for methods to return `self` (invisibly) when possible, because it makes them chainable. For example, the `add()` method returns `self` so you can chain them together: - -```{r} -q$add(10)$add(11)$add(12) -``` - -On the other hand, `remove()` returns the value removed, so it's not chainable: - -```{r} -q$remove() -q$remove() -q$remove() -q$remove() -``` - - -### Active bindings - -Active bindings look like fields, but each time they are accessed, they call a function. They are always publicly visible. - -```{r} -Numbers <- R6Class("Numbers", - public = list( - x = 100 - ), - active = list( - x2 = function(value) { - if (missing(value)) return(self$x * 2) - else self$x <- value/2 - }, - rand = function() rnorm(1) - ) -) - -n <- Numbers$new() -n$x -``` - -When an active binding is accessed as if reading a value, it calls the function with `value` as a missing argument: - -```{r} -n$x2 -``` - -When it's accessed as if assigning a value, it uses the assignment value as the `value` argument: - -```{r} -n$x2 <- 1000 -n$x -``` - -If the function takes no arguments, it's not possible to use it with `<-`: - -```{r eval=FALSE} -n$rand -#> [1] 0.2648 -n$rand -#> [1] 2.171 -n$rand <- 3 -#> Error: unused argument (quote(3)) -``` - -Implementation note: Active bindings are bound in the public environment. The enclosing environment for these functions is also the public environment. - -### Inheritance - -One R6 class can inherit from another. In other words, you can have super- and sub-classes. - -Subclasses can have additional methods, and they can also have methods that override the superclass methods. In this example of a queue that retains its history, we'll add a `show()` method and override the `remove()` method: - -```{r} -# Note that this isn't very efficient - it's just for illustrating inheritance. -HistoryQueue <- R6Class("HistoryQueue", - inherit = Queue, - public = list( - show = function() { - cat("Next item is at index", private$head_idx + 1, "\n") - for (i in seq_along(private$queue)) { - cat(i, ": ", private$queue[[i]], "\n", sep = "") - } - }, - remove = function() { - if (private$length() - private$head_idx == 0) return(NULL) - private$head_idx <<- private$head_idx + 1 - private$queue[[private$head_idx]] - } - ), - private = list( - head_idx = 0 - ) -) - -hq <- HistoryQueue$new(5, 6, "foo") -hq$show() -hq$remove() -hq$show() -hq$remove() -``` - -Superclass methods can be called with `super$xx()`. The `CountingQueue` (example below) keeps a count of the total number of objects that have ever been added to the queue. It does this by overriding the `add()` method -- it increments a counter and then calls the superclass's `add()` method, with `super$add(x)`: - -```{r} -CountingQueue <- R6Class("CountingQueue", - inherit = Queue, - public = list( - add = function(x) { - private$total <<- private$total + 1 - super$add(x) - }, - get_total = function() private$total - ), - private = list( - total = 0 - ) -) - -cq <- CountingQueue$new("x", "y") -cq$get_total() -cq$add("z") -cq$remove() -cq$remove() -cq$get_total() -``` - - -### Fields containing reference objects - -If your R6 class contains any fields that also have reference semantics (e.g., other R6 objects, and environments), those fields should be populated in the `initialize` method. If the field set to the reference object directly in the class definition, that object will be shared across all instances of the R6 objects. Here's an example: - -```{r} -SimpleClass <- R6Class("SimpleClass", - public = list(x = NULL) -) - -SharedField <- R6Class("SharedField", - public = list( - e = SimpleClass$new() - ) -) - -s1 <- SharedField$new() -s1$e$x <- 1 - -s2 <- SharedField$new() -s2$e$x <- 2 - -# Changing s2$e$x has changed the value of s1$e$x -s1$e$x -``` - -To avoid this, populate the field in the `initialize` method: - -```{r} -NonSharedField <- R6Class("NonSharedField", - public = list( - e = NULL, - initialize = function() self$e <- SimpleClass$new() - ) -) - -n1 <- NonSharedField$new() -n1$e$x <- 1 - -n2 <- NonSharedField$new() -n2$e$x <- 2 - -# n2$e$x does not affect n1$e$x -n1$e$x -``` - - -## Portable and non-portable classes - -In R6 version 1.0.1, the default was to create **non-portable** classes. In subsequent versions, the default is to create **portable** classes. The two most noticeable differences are that portable classes: - -* Support inheritance across different packages. Non-portable classes do not do this very well. -* Always require the use of `self` and `private` to access members, as in `self$x` and `private$y`. Non-portable classes can access these members with just `x` and `y`, and do assignment to these members with the `<<-` operator. - -The implementation of the first point is such that it makes the second point necessary. - -### Using `self` and `<<-` - -With reference classes, you can access the field without `self`, and assign to fields using `<<-`. For example: - -```{r} -RC <- setRefClass("RC", - fields = list(x = 'ANY'), - methods = list( - getx = function() x, - setx = function(value) x <<- value - ) -) - -rc <- RC$new() -rc$setx(10) -rc$getx() -``` - -The same is true for non-portable R6 classes: - -```{r} -NP <- R6Class("NP", - portable = FALSE, - public = list( - x = NA, - getx = function() x, - setx = function(value) x <<- value - ) -) - -np <- NP$new() -np$setx(10) -np$getx() -``` - -But for portable R6 classes (this is the default), you must use `self` and/or `private`, and `<<-` assignment doesn't work -- unless you use `self`, of course: - - -```{r} -P <- R6Class("P", - portable = TRUE, # This is default - public = list( - x = NA, - getx = function() self$x, - setx = function(value) self$x <- value - ) -) - -p <- P$new() -p$setx(10) -p$getx() -``` - -For more information, see the Portable vignette. - - -## Other topics - -### Adding members to an existing class - -It is sometimes useful to add members to a class after the class has already been created. This can be done using the `$set()` method on the generator object. - -```{r} -Simple <- R6Class("Simple", - public = list( - x = 1, - getx = function() self$x - ) -) - -Simple$set("public", "getx2", function() self$x*2) - -# To replace an existing member, use overwrite=TRUE -Simple$set("public", "x", 10, overwrite = TRUE) - -s <- Simple$new() -s$x -s$getx2() -``` - -The new members will be present only in instances that are created after `$set()` has been called. - -To prevent modification of a class, you can use `lock_class=TRUE` when creating the class. You can also lock and unlock a class as follows: - -```{r} -# Create a locked class -Simple <- R6Class("Simple", - public = list( - x = 1, - getx = function() self$x - ), - lock_class = TRUE -) - -# This would result in an error -# Simple$set("public", "y", 2) - -# Unlock the class -Simple$unlock() - -# Now it works -Simple$set("public", "y", 2) - -# Lock the class again -Simple$lock() -``` - - -### Cloning objects - -By default, R6 objects have method named `clone` for making a copy of the object. - -```{r} -Simple <- R6Class("Simple", - public = list( - x = 1, - getx = function() self$x - ) -) - -s <- Simple$new() - -# Create a clone -s1 <- s$clone() -# Modify it -s1$x <- 2 -s1$getx() - -# Original is unaffected by changes to the clone -s$getx() -``` - -```{r clone-size, echo=FALSE} -# Calculate size of clone method in this block. -Cloneable <- R6Class("Cloneable", cloneable = TRUE) -NonCloneable <- R6Class("NonCloneable", cloneable = FALSE) - -c1 <- Cloneable$new() -c2 <- Cloneable$new() -# Bytes for each new cloneable object -cloneable_delta <- object_size(c1, c2) - object_size(c2) - -nc1 <- NonCloneable$new() -nc2 <- NonCloneable$new() -# Bytes for each new noncloneable object -noncloneable_delta <- object_size(nc1, nc2) - object_size(nc2) - -# Number of bytes used by each copy of clone method -additional_clone_method_bytes <- cloneable_delta - noncloneable_delta -additional_clone_method_bytes_str <- capture.output(print(additional_clone_method_bytes)) - -# Number of bytes used by first copy of a clone method -first_clone_method_bytes <- object_size(c1) - object_size(nc1) -# Need some trickery to get the nice output from pryr::print.bytes -first_clone_method_bytes_str <- capture.output(print(first_clone_method_bytes)) -``` - -If you don't want a `clone` method to be added, you can use `cloneable=FALSE` when creating the class. If any loaded R6 object has a `clone` method, that function uses `r first_clone_method_bytes_str`, but for each additional object, the `clone` method costs a trivial amount of space (`r additional_clone_method_bytes` bytes). - - -#### Deep cloning - -If there are any fields which are objects with reference sematics (environments, R6 objects, reference class objects), the copy will get a reference to the same object. This is sometimes desirable, but often it is not. - -For example, we'll create an object `c1` which contains another R6 object, `s`, and then clone it. Because the original's and the clone's `s` fields both refer to the same object, modifying it from one results in a change that is reflect in the other. - -```{r} -Simple <- R6Class("Simple", public = list(x = 1)) - -Cloneable <- R6Class("Cloneable", - public = list( - s = NULL, - initialize = function() self$s <- Simple$new() - ) -) - -c1 <- Cloneable$new() -c2 <- c1$clone() - -# Change c1's `s` field -c1$s$x <- 2 - -# c2's `s` is the same object, so it reflects the change -c2$s$x -``` - -To make it so the clone receives a *copy* of `s`, we can use the `deep=TRUE` option: - -```{r} -c3 <- c1$clone(deep = TRUE) - -# Change c1's `s` field -c1$s$x <- 3 - -# c2's `s` is different -c3$s$x -``` - -The default behavior of `clone(deep=TRUE)` is to copy fields which are R6 objects, but not copy fields which are environments, reference class objects, or other data structures which contain other reference-type objects (for example, a list with an R6 object). - -If your R6 object contains these types of objects and you want to make a deep clone of them, you must provide your own function for deep cloning, in a private method named `deep_clone`. Below is an example of an R6 object with two fields, `a` and `b`, both of which which are environments, and both of which contain a value `x`. It also has a field `v` which is a regular (non-reference) value, and a private `deep_clone` method. - -The `deep_clone` method is be called once for each field. It is passed the name and value of the field, and the value it returns is be used in the clone. - -```{r} -CloneEnv <- R6Class("CloneEnv", - public = list( - a = NULL, - b = NULL, - v = 1, - initialize = function() { - self$a <- new.env(parent = emptyenv()) - self$b <- new.env(parent = emptyenv()) - self$a$x <- 1 - self$b$x <- 1 - } - ), - private = list( - deep_clone = function(name, value) { - # With x$clone(deep=TRUE) is called, the deep_clone gets invoked once for - # each field, with the name and value. - if (name == "a") { - # `a` is an environment, so use this quick way of copying - list2env(as.list.environment(value, all.names = TRUE), - parent = emptyenv()) - } else { - # For all other fields, just return the value - value - } - } - ) -) - -c1 <- CloneEnv$new() -c2 <- c1$clone(deep = TRUE) -``` - -When `c1$clone(deep=TRUE)` is called, the `deep_clone` method is called for each field in `c1`, and is passed the name of the field and value. In our version, the `a` environment gets copied, but `b` does not, nor does `v` (but that doesn't matter since `v` is not a reference object). We can test out the clone: - -```{r} -# Modifying c1$a doesn't affect c2$a, because they're separate objects -c1$a$x <- 2 -c2$a$x - -# Modifying c1$b does affect c2$b, because they're the same object -c1$b$x <- 3 -c2$b$x - -# Modifying c1$v doesn't affect c2$v, because they're not reference objects -c1$v <- 4 -c2$v -``` - -In the example `deep_clone` method above, we checked the name of each field to determine what to do with it, but we could also check the value, by using `inherits(value, "R6")`, or `is.environment()`, and so on. - - -### Printing R6 objects to the screen - -R6 objects have a default `print` method that lists all members of the object. -If a class defines a `print` method, then it overrides the default one. - -```{r} -PrettyCountingQueue <- R6Class("PrettyCountingQueue", - inherit = CountingQueue, - public = list( - print = function(...) { - cat(" of ", self$get_total(), " elements\n", sep = "") - invisible(self) - } - ) -) -``` - -```{r} -pq <- PrettyCountingQueue$new(1, 2, "foobar") -pq -``` - -### Finalizers - -Sometimes it's useful to run a function when the object is garbage collected. For example, you may want to make sure a file or database connection gets closed. To do this, you can define a `finalize()` method, which will be called with no arguments when the object is garbage collected. - - -```{r} -A <- R6Class("A", public = list( - finalize = function() { - print("Finalizer has been called!") - } -)) - - -# Instantiate an object: -obj <- A$new() - -# Remove the single existing reference to it, and force garbage collection -# (normally garbage collection will happen automatically from time -# to time) -rm(obj); gc() -``` - -Finalizers are implemented using the `reg.finalizer()` function, and they set `onexit=TRUE`, so that the finalizer will also be called when R exits. This is useful in some cases, like database connections. - - -## Summary - -R6 classes provide capabilities that are common in other object-oriented programming languages. They're similar to R's built-in reference classes, but are simpler, smaller, and faster, and they allow inheritance across packages. diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Introduction.html b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Introduction.html deleted file mode 100644 index f92d2af..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Introduction.html +++ /dev/null @@ -1,584 +0,0 @@ - - - - - - - - - - - - - - -Introduction to R6 classes - - - - - - - - - - - - - - - - - - - -

Introduction to R6 classes

- - - - -

The R6 package provides a type of class which is similar to R’s standard reference classes, but it is more efficient and doesn’t depend on S4 classes and the methods package.

-
-

R6 classes

-

R6 classes are similar to R’s standard reference classes, but are lighter weight, and avoid some issues that come along with using S4 classes (R’s reference classes are based on S4). For more information about speed and memory footprint, see the Performance vignette.

-

Unlike many objects in R, instances (objects) of R6 classes have reference semantics. R6 classes also support:

-
    -
  • public and private methods
  • -
  • active bindings
  • -
  • inheritance (superclasses) which works across packages
  • -
-

Why the name R6? When R’s reference classes were introduced, some users, following the names of R’s existing class systems S3 and S4, called the new class system R5 in jest. Although reference classes are not actually called R5, the name of this package and its classes takes inspiration from that name.

-

The name R5 was also a code-name used for a different object system started by Simon Urbanek, meant to solve some issues with S4 relating to syntax and performance. However, the R5 branch was shelved after a little development, and it was never released.

-
-

Basics

-

Here’s how to create a simple R6 class. The public argument is a list of items, which can be functions and fields (non-functions). Functions will be used as methods.

-
library(R6)
-
-Person <- R6Class("Person",
-  public = list(
-    name = NULL,
-    hair = NULL,
-    initialize = function(name = NA, hair = NA) {
-      self$name <- name
-      self$hair <- hair
-      self$greet()
-    },
-    set_hair = function(val) {
-      self$hair <- val
-    },
-    greet = function() {
-      cat(paste0("Hello, my name is ", self$name, ".\n"))
-    }
-  )
-)
-

To instantiate an object of this class, use $new():

-
ann <- Person$new("Ann", "black")
-#> Hello, my name is Ann.
-ann
-#> <Person>
-#>   Public:
-#>     clone: function (deep = FALSE) 
-#>     greet: function () 
-#>     hair: black
-#>     initialize: function (name = NA, hair = NA) 
-#>     name: Ann
-#>     set_hair: function (val)
-

The $new() method creates the object and calls the initialize() method, if it exists.

-

Inside methods of the class, self refers to the object. Public members of the object (all you’ve seen so far) are accessed with self$x, and assignment is done with self$x <- y. Note that by default, self is required to access members, although for non-portable classes which we’ll see later, it is optional.

-

Once the object is instantiated, you can access values and methods with $:

-
ann$hair
-#> [1] "black"
-ann$greet()
-#> Hello, my name is Ann.
-ann$set_hair("red")
-ann$hair
-#> [1] "red"
-

Implementation note: The external face of an R6 object is basically an environment with the public members in it. This is also known as the public environment. An R6 object’s methods have a separate enclosing environment which, roughly speaking, is the environment they “run in”. This is where self binding is found, and it is simply a reference back to public environment.

-
-
-

Private members

-

In the previous example, all the members were public. It’s also possible to add private members:

-
Queue <- R6Class("Queue",
-  public = list(
-    initialize = function(...) {
-      for (item in list(...)) {
-        self$add(item)
-      }
-    },
-    add = function(x) {
-      private$queue <- c(private$queue, list(x))
-      invisible(self)
-    },
-    remove = function() {
-      if (private$length() == 0) return(NULL)
-      # Can use private$queue for explicit access
-      head <- private$queue[[1]]
-      private$queue <- private$queue[-1]
-      head
-    }
-  ),
-  private = list(
-    queue = list(),
-    length = function() base::length(private$queue)
-  )
-)
-
-q <- Queue$new(5, 6, "foo")
-

Whereas public members are accessed with self, like self$add(), private members are accessed with private, like private$queue.

-

The public members can be accessed as usual:

-
# Add and remove items
-q$add("something")
-q$add("another thing")
-q$add(17)
-q$remove()
-#> [1] 5
-q$remove()
-#> [1] 6
-

However, private members can’t be accessed directly:

-
q$queue
-#> NULL
-q$length()
-#> Error: attempt to apply non-function
-

A useful design pattern is for methods to return self (invisibly) when possible, because it makes them chainable. For example, the add() method returns self so you can chain them together:

-
q$add(10)$add(11)$add(12)
-

On the other hand, remove() returns the value removed, so it’s not chainable:

-
q$remove()
-#> [1] "foo"
-q$remove()
-#> [1] "something"
-q$remove()
-#> [1] "another thing"
-q$remove()
-#> [1] 17
-
-
-

Active bindings

-

Active bindings look like fields, but each time they are accessed, they call a function. They are always publicly visible.

-
Numbers <- R6Class("Numbers",
-  public = list(
-    x = 100
-  ),
-  active = list(
-    x2 = function(value) {
-      if (missing(value)) return(self$x * 2)
-      else self$x <- value/2
-    },
-    rand = function() rnorm(1)
-  )
-)
-
-n <- Numbers$new()
-n$x
-#> [1] 100
-

When an active binding is accessed as if reading a value, it calls the function with value as a missing argument:

-
n$x2
-#> [1] 200
-

When it’s accessed as if assigning a value, it uses the assignment value as the value argument:

-
n$x2 <- 1000
-n$x
-#> [1] 500
-

If the function takes no arguments, it’s not possible to use it with <-:

-
n$rand
-#> [1] 0.2648
-n$rand
-#> [1] 2.171
-n$rand <- 3
-#> Error: unused argument (quote(3))
-

Implementation note: Active bindings are bound in the public environment. The enclosing environment for these functions is also the public environment.

-
-
-

Inheritance

-

One R6 class can inherit from another. In other words, you can have super- and sub-classes.

-

Subclasses can have additional methods, and they can also have methods that override the superclass methods. In this example of a queue that retains its history, we’ll add a show() method and override the remove() method:

-
# Note that this isn't very efficient - it's just for illustrating inheritance.
-HistoryQueue <- R6Class("HistoryQueue",
-  inherit = Queue,
-  public = list(
-    show = function() {
-      cat("Next item is at index", private$head_idx + 1, "\n")
-      for (i in seq_along(private$queue)) {
-        cat(i, ": ", private$queue[[i]], "\n", sep = "")
-      }
-    },
-    remove = function() {
-      if (private$length() - private$head_idx == 0) return(NULL)
-      private$head_idx <<- private$head_idx + 1
-      private$queue[[private$head_idx]]
-    }
-  ),
-  private = list(
-    head_idx = 0
-  )
-)
-
-hq <- HistoryQueue$new(5, 6, "foo")
-hq$show()
-#> Next item is at index 1 
-#> 1: 5
-#> 2: 6
-#> 3: foo
-hq$remove()
-#> [1] 5
-hq$show()
-#> Next item is at index 2 
-#> 1: 5
-#> 2: 6
-#> 3: foo
-hq$remove()
-#> [1] 6
-

Superclass methods can be called with super$xx(). The CountingQueue (example below) keeps a count of the total number of objects that have ever been added to the queue. It does this by overriding the add() method – it increments a counter and then calls the superclass’s add() method, with super$add(x):

-
CountingQueue <- R6Class("CountingQueue",
-  inherit = Queue,
-  public = list(
-    add = function(x) {
-      private$total <<- private$total + 1
-      super$add(x)
-    },
-    get_total = function() private$total
-  ),
-  private = list(
-    total = 0
-  )
-)
-
-cq <- CountingQueue$new("x", "y")
-cq$get_total()
-#> [1] 2
-cq$add("z")
-cq$remove()
-#> [1] "x"
-cq$remove()
-#> [1] "y"
-cq$get_total()
-#> [1] 3
-
-
-

Fields containing reference objects

-

If your R6 class contains any fields that also have reference semantics (e.g., other R6 objects, and environments), those fields should be populated in the initialize method. If the field set to the reference object directly in the class definition, that object will be shared across all instances of the R6 objects. Here’s an example:

-
SimpleClass <- R6Class("SimpleClass",
-  public = list(x = NULL)
-)
-
-SharedField <- R6Class("SharedField",
-  public = list(
-    e = SimpleClass$new()
-  )
-)
-
-s1 <- SharedField$new()
-s1$e$x <- 1
-
-s2 <- SharedField$new()
-s2$e$x <- 2
-
-# Changing s2$e$x has changed the value of s1$e$x
-s1$e$x
-#> [1] 2
-

To avoid this, populate the field in the initialize method:

-
NonSharedField <- R6Class("NonSharedField",
-  public = list(
-    e = NULL,
-    initialize = function() self$e <- SimpleClass$new()
-  )
-)
-
-n1 <- NonSharedField$new()
-n1$e$x <- 1
-
-n2 <- NonSharedField$new()
-n2$e$x <- 2
-
-# n2$e$x does not affect n1$e$x
-n1$e$x
-#> [1] 1
-
-
-
-

Portable and non-portable classes

-

In R6 version 1.0.1, the default was to create non-portable classes. In subsequent versions, the default is to create portable classes. The two most noticeable differences are that portable classes:

-
    -
  • Support inheritance across different packages. Non-portable classes do not do this very well.
  • -
  • Always require the use of self and private to access members, as in self$x and private$y. Non-portable classes can access these members with just x and y, and do assignment to these members with the <<- operator.
  • -
-

The implementation of the first point is such that it makes the second point necessary.

-
-

Using self and <<-

-

With reference classes, you can access the field without self, and assign to fields using <<-. For example:

-
RC <- setRefClass("RC",
-  fields = list(x = 'ANY'),
-  methods = list(
-    getx = function() x,
-    setx = function(value) x <<- value
-  )
-)
-
-rc <- RC$new()
-rc$setx(10)
-rc$getx()
-#> [1] 10
-

The same is true for non-portable R6 classes:

-
NP <- R6Class("NP",
-  portable = FALSE,
-  public = list(
-    x = NA,
-    getx = function() x,
-    setx = function(value) x <<- value
-  )
-)
-
-np <- NP$new()
-np$setx(10)
-np$getx()
-#> [1] 10
-

But for portable R6 classes (this is the default), you must use self and/or private, and <<- assignment doesn’t work – unless you use self, of course:

-
P <- R6Class("P",
-  portable = TRUE,  # This is default
-  public = list(
-    x = NA,
-    getx = function() self$x,
-    setx = function(value) self$x <- value
-  )
-)
-
-p <- P$new()
-p$setx(10)
-p$getx()
-#> [1] 10
-

For more information, see the Portable vignette.

-
-
-
-

Other topics

-
-

Adding members to an existing class

-

It is sometimes useful to add members to a class after the class has already been created. This can be done using the $set() method on the generator object.

-
Simple <- R6Class("Simple",
-  public = list(
-    x = 1,
-    getx = function() self$x
-  )
-)
-
-Simple$set("public", "getx2", function() self$x*2)
-
-# To replace an existing member, use overwrite=TRUE
-Simple$set("public", "x", 10, overwrite = TRUE)
-
-s <- Simple$new()
-s$x
-#> [1] 10
-s$getx2()
-#> [1] 20
-

The new members will be present only in instances that are created after $set() has been called.

-

To prevent modification of a class, you can use lock_class=TRUE when creating the class. You can also lock and unlock a class as follows:

-
# Create a locked class
-Simple <- R6Class("Simple",
-  public = list(
-    x = 1,
-    getx = function() self$x
-  ),
-  lock_class = TRUE
-)
-
-# This would result in an error
-# Simple$set("public", "y", 2)
-
-# Unlock the class
-Simple$unlock()
-
-# Now it works
-Simple$set("public", "y", 2)
-
-# Lock the class again
-Simple$lock()
-
-
-

Cloning objects

-

By default, R6 objects have method named clone for making a copy of the object.

-
Simple <- R6Class("Simple",
-  public = list(
-    x = 1,
-    getx = function() self$x
-  )
-)
-
-s <- Simple$new()
-
-# Create a clone
-s1 <- s$clone()
-# Modify it
-s1$x <- 2
-s1$getx()
-#> [1] 2
-
-# Original is unaffected by changes to the clone
-s$getx()
-#> [1] 1
-

If you don’t want a clone method to be added, you can use cloneable=FALSE when creating the class. If any loaded R6 object has a clone method, that function uses 48.1 kB, but for each additional object, the clone method costs a trivial amount of space (112 bytes).

-
-

Deep cloning

-

If there are any fields which are objects with reference sematics (environments, R6 objects, reference class objects), the copy will get a reference to the same object. This is sometimes desirable, but often it is not.

-

For example, we’ll create an object c1 which contains another R6 object, s, and then clone it. Because the original’s and the clone’s s fields both refer to the same object, modifying it from one results in a change that is reflect in the other.

-
Simple <- R6Class("Simple", public = list(x = 1))
-
-Cloneable <- R6Class("Cloneable",
-  public = list(
-    s = NULL,
-    initialize = function() self$s <- Simple$new()
-  )
-)
-
-c1 <- Cloneable$new()
-c2 <- c1$clone()
-
-# Change c1's `s` field
-c1$s$x <- 2
-
-# c2's `s` is the same object, so it reflects the change
-c2$s$x
-#> [1] 2
-

To make it so the clone receives a copy of s, we can use the deep=TRUE option:

-
c3 <- c1$clone(deep = TRUE)
-
-# Change c1's `s` field
-c1$s$x <- 3
-
-# c2's `s` is different
-c3$s$x
-#> [1] 2
-

The default behavior of clone(deep=TRUE) is to copy fields which are R6 objects, but not copy fields which are environments, reference class objects, or other data structures which contain other reference-type objects (for example, a list with an R6 object).

-

If your R6 object contains these types of objects and you want to make a deep clone of them, you must provide your own function for deep cloning, in a private method named deep_clone. Below is an example of an R6 object with two fields, a and b, both of which which are environments, and both of which contain a value x. It also has a field v which is a regular (non-reference) value, and a private deep_clone method.

-

The deep_clone method is be called once for each field. It is passed the name and value of the field, and the value it returns is be used in the clone.

-
CloneEnv <- R6Class("CloneEnv",
-  public = list(
-    a = NULL,
-    b = NULL,
-    v = 1,
-    initialize = function() {
-      self$a <- new.env(parent = emptyenv())
-      self$b <- new.env(parent = emptyenv())
-      self$a$x <- 1
-      self$b$x <- 1
-    }
-  ),
-  private = list(
-    deep_clone = function(name, value) {
-      # With x$clone(deep=TRUE) is called, the deep_clone gets invoked once for
-      # each field, with the name and value.
-      if (name == "a") {
-        # `a` is an environment, so use this quick way of copying
-        list2env(as.list.environment(value, all.names = TRUE),
-                 parent = emptyenv())
-      } else {
-        # For all other fields, just return the value
-        value
-      }
-    }
-  )
-)
-
-c1 <- CloneEnv$new()
-c2 <- c1$clone(deep = TRUE)
-

When c1$clone(deep=TRUE) is called, the deep_clone method is called for each field in c1, and is passed the name of the field and value. In our version, the a environment gets copied, but b does not, nor does v (but that doesn’t matter since v is not a reference object). We can test out the clone:

-
# Modifying c1$a doesn't affect c2$a, because they're separate objects
-c1$a$x <- 2
-c2$a$x
-#> [1] 1
-
-# Modifying c1$b does affect c2$b, because they're the same object
-c1$b$x <- 3
-c2$b$x
-#> [1] 3
-
-# Modifying c1$v doesn't affect c2$v, because they're not reference objects
-c1$v <- 4
-c2$v
-#> [1] 1
-

In the example deep_clone method above, we checked the name of each field to determine what to do with it, but we could also check the value, by using inherits(value, "R6"), or is.environment(), and so on.

-
-
-
-

Printing R6 objects to the screen

-

R6 objects have a default print method that lists all members of the object. If a class defines a print method, then it overrides the default one.

-
PrettyCountingQueue <- R6Class("PrettyCountingQueue",
-  inherit = CountingQueue,
-  public = list(
-    print = function(...) {
-      cat("<PrettyCountingQueue> of ", self$get_total(), " elements\n", sep = "")
-      invisible(self)
-    }
-  )
-)
-
pq <- PrettyCountingQueue$new(1, 2, "foobar")
-pq
-#> <PrettyCountingQueue> of 3 elements
-
-
-

Finalizers

-

Sometimes it’s useful to run a function when the object is garbage collected. For example, you may want to make sure a file or database connection gets closed. To do this, you can define a finalize() method, which will be called with no arguments when the object is garbage collected.

-
A <- R6Class("A", public = list(
-  finalize = function() {
-    print("Finalizer has been called!")
-  }
-))
-
-
-# Instantiate an object:
-obj <- A$new()
-
-# Remove the single existing reference to it, and force garbage collection
-# (normally garbage collection will happen automatically from time
-# to time)
-rm(obj); gc()
-#> [1] "Finalizer has been called!"
-#>           used (Mb) gc trigger (Mb) max used (Mb)
-#> Ncells  550905 29.5     940480 50.3   940480 50.3
-#> Vcells 1072054  8.2    2060183 15.8  1489990 11.4
-

Finalizers are implemented using the reg.finalizer() function, and they set onexit=TRUE, so that the finalizer will also be called when R exits. This is useful in some cases, like database connections.

-
-
-
-

Summary

-

R6 classes provide capabilities that are common in other object-oriented programming languages. They’re similar to R’s built-in reference classes, but are simpler, smaller, and faster, and they allow inheritance across packages.

-
- - - - - - - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Performance.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Performance.R deleted file mode 100644 index 8c6d49e..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Performance.R +++ /dev/null @@ -1,518 +0,0 @@ -## ----echo = FALSE-------------------------------------------------------- -knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 3.9, fig.height = 3.5) - -# Make sure vignette doesn't error on platforms where microbenchmark is not present. -if (requireNamespace("microbenchmark", quietly = TRUE)) { - library(microbenchmark) - - # Only print 3 significant digits - print_microbenchmark <- function (x, unit, order = NULL, ...) { - s <- summary(x, unit = unit) - cat("Unit: ", attr(s, "unit"), "\n", sep = "") - - timing_cols <- c("min", "lq", "median", "uq", "max") - s[timing_cols] <- lapply(s[timing_cols], signif, digits = 3) - s[timing_cols] <- lapply(s[timing_cols], format, big.mark = ",") - - print(s, ..., row.names = FALSE) - } - - assignInNamespace("print.microbenchmark", print_microbenchmark, - "microbenchmark") - -} else { - # Some dummy functions so that the vignette doesn't throw an error. - microbenchmark <- function(...) { - structure(list(), class = "microbenchmark_dummy") - } - - summary.microbenchmark_dummy <- function(object, ...) { - data.frame(expr = "", median = 0) - } -} - -## ----eval = FALSE-------------------------------------------------------- -# library(microbenchmark) -# options(microbenchmark.unit = "us") -# library(pryr) # For object_size function -# library(R6) - -## ----echo = FALSE-------------------------------------------------------- -# The previous code block is just for appearances. This code block is the one -# that gets run. The loading of microbenchmark must be conditional because it is -# not available on all platforms. -if (requireNamespace("microbenchmark", quietly = TRUE)) { - library(microbenchmark) -} -options(microbenchmark.unit = "us") -library(pryr) # For object_size function -library(R6) - -## ----echo=FALSE---------------------------------------------------------- -library(ggplot2) -library(scales) - -# Set up ggplot2 theme -my_theme <- theme_bw(base_size = 10) + - theme(axis.title.x = element_blank(), - axis.title.y = element_blank(), - panel.grid.major.y = element_blank(), - panel.grid.minor.y = element_blank() - ) - -## ------------------------------------------------------------------------ -RC <- setRefClass("RC", - fields = list(x = "numeric"), - methods = list( - initialize = function(x = 1) .self$x <- x, - getx = function() x, - inc = function(n = 1) x <<- x + n - ) -) - -## ------------------------------------------------------------------------ -RC$new() - -## ------------------------------------------------------------------------ -R6 <- R6Class("R6", - public = list( - x = NULL, - initialize = function(x = 1) self$x <- x, - getx = function() self$x, - inc = function(n = 1) self$x <- x + n - ) -) - -## ------------------------------------------------------------------------ -R6$new() - -## ------------------------------------------------------------------------ -R6NoClass <- R6Class("R6NoClass", - class = FALSE, - public = list( - x = NULL, - initialize = function(x = 1) self$x <- x, - getx = function() self$x, - inc = function(n = 1) self$x <- self$x + n - ) -) - -## ------------------------------------------------------------------------ -R6NonPortable <- R6Class("R6NonPortable", - portable = FALSE, - public = list( - x = NULL, - initialize = function(value = 1) x <<- value, - getx = function() x, - inc = function(n = 1) x <<- x + n - ) -) - -## ------------------------------------------------------------------------ -R6NonCloneable <- R6Class("R6NonCloneable", - cloneable = FALSE, - public = list( - x = NULL, - initialize = function(x = 1) self$x <- x, - getx = function() self$x, - inc = function(n = 1) self$x <- self$x + n - ) -) - -## ------------------------------------------------------------------------ -R6Bare <- R6Class("R6Bare", - portable = FALSE, - class = FALSE, - cloneable = FALSE, - public = list( - x = NULL, - initialize = function(value = 1) x <<- value, - getx = function() x, - inc = function(n = 1) x <<- x + n - ) -) - -## ------------------------------------------------------------------------ -R6Private <- R6Class("R6Private", - private = list(x = NULL), - public = list( - initialize = function(x = 1) private$x <- x, - getx = function() private$x, - inc = function(n = 1) private$x <- private$x + n - ) -) - -## ------------------------------------------------------------------------ -R6Private$new() - -## ------------------------------------------------------------------------ -R6PrivateBare <- R6Class("R6PrivateBare", - portable = FALSE, - class = FALSE, - cloneable = FALSE, - private = list(x = NULL), - public = list( - initialize = function(x = 1) private$x <- x, - getx = function() x, - inc = function(n = 1) x <<- x + n - ) -) - -## ------------------------------------------------------------------------ -FunctionEnvClass <- function(x = 1) { - inc <- function(n = 1) x <<- x + n - getx <- function() x - self <- environment() - class(self) <- "FunctionEnvClass" - self -} - -## ------------------------------------------------------------------------ -ls(FunctionEnvClass()) - -## ------------------------------------------------------------------------ -FunctionEnvNoClass <- function(x = 1) { - inc <- function(n = 1) x <<- x + n - getx <- function() x - environment() -} - -## ------------------------------------------------------------------------ -ls(FunctionEnvNoClass()) - -## ----echo = FALSE-------------------------------------------------------- -# Utility functions for calculating sizes -obj_size <- function(expr, .env = parent.frame()) { - size_n <- function(n = 1) { - objs <- lapply(1:n, function(x) eval(expr, .env)) - as.numeric(do.call(object_size, objs)) - } - - data.frame(one = size_n(1), incremental = size_n(2) - size_n(1)) -} - -obj_sizes <- function(..., .env = parent.frame()) { - exprs <- as.list(match.call(expand.dots = FALSE)$...) - names(exprs) <- lapply(1:length(exprs), - FUN = function(n) { - name <- names(exprs)[n] - if (is.null(name) || name == "") paste(deparse(exprs[[n]]), collapse = " ") - else name - }) - - sizes <- mapply(obj_size, exprs, MoreArgs = list(.env = .env), SIMPLIFY = FALSE) - do.call(rbind, sizes) -} - -## ------------------------------------------------------------------------ -sizes <- obj_sizes( - RC$new(), - R6$new(), - R6NoClass$new(), - R6NonPortable$new(), - R6NonCloneable$new(), - R6Bare$new(), - R6Private$new(), - R6PrivateBare$new(), - FunctionEnvClass(), - FunctionEnvNoClass() -) -sizes - -## ----echo = FALSE, results = 'hold'-------------------------------------- -objnames <- c( - "RC", "R6", "R6NoClass", "R6NonPortable", "R6NonCloneable", - "R6Bare", "R6Private", "R6PrivateBare", "FunctionEnvClass", - "FunctionEnvNoClass" -) - -obj_labels <- objnames -obj_labels[1] <- "RC (off chart)" - -sizes$name <- factor(objnames, levels = rev(objnames)) - -ggplot(sizes, aes(y = name, x = one)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - scale_x_continuous(limits = c(0, max(sizes$one[-1]) * 1.5), - expand = c(0, 0), oob = rescale_none) + - scale_y_discrete( - breaks = sizes$name, - labels = obj_labels) + - my_theme + - ggtitle("First object") - -ggplot(sizes, aes(y = name, x = incremental)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - scale_x_continuous(limits = c(0, max(sizes$incremental) * 1.05), - expand = c(0, 0)) + - geom_point(size = 2) + - my_theme + - ggtitle("Additional objects") - -## ------------------------------------------------------------------------ -RC2 <- setRefClass("RC2", - fields = list(x = "numeric"), - methods = list( - initialize = function(x = 2) .self$x <<- x, - inc = function(n = 2) x <<- x * n - ) -) - -# Calcualte the size of a new RC2 object, over and above an RC object -as.numeric(object_size(RC$new(), RC2$new()) - object_size(RC$new())) - -## ------------------------------------------------------------------------ -# Function to extract the medians from microbenchmark results -mb_summary <- function(x) { - res <- summary(x, unit="us") - data.frame(name = res$expr, median = res$median) -} - -speed <- microbenchmark( - RC$new(), - R6$new(), - R6NoClass$new(), - R6NonPortable$new(), - R6NonCloneable$new(), - R6Bare$new(), - R6Private$new(), - R6PrivateBare$new(), - FunctionEnvClass(), - FunctionEnvNoClass() -) -speed <- mb_summary(speed) -speed - -## ----echo = FALSE, results = 'hold', fig.width = 8----------------------- -speed$name <- factor(speed$name, rev(levels(speed$name))) - -p <- ggplot(speed, aes(y = name, x = median)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - scale_x_continuous(limits = c(0, max(speed$median) * 1.05), expand = c(0, 0)) + - my_theme + - ggtitle("Median time to instantiate object (\u0b5s)") - -p - -## ------------------------------------------------------------------------ -rc <- RC$new() -r6 <- R6$new() -r6noclass <- R6NoClass$new() -r6noport <- R6NonPortable$new() -r6noclone <- R6NonCloneable$new() -r6bare <- R6Bare$new() -r6priv <- R6Private$new() -r6priv_bare <- R6PrivateBare$new() -fun_env <- FunctionEnvClass() -fun_env_nc <- FunctionEnvNoClass() - -## ------------------------------------------------------------------------ -speed <- microbenchmark( - rc$x, - r6$x, - r6noclass$x, - r6noport$x, - r6noclone$x, - r6bare$x, - r6priv$x, - r6priv_bare$x, - fun_env$x, - fun_env_nc$x -) -speed <- mb_summary(speed) -speed - -## ----echo = FALSE, results = 'hold', fig.width = 8----------------------- -speed$name <- factor(speed$name, rev(levels(speed$name))) - -p <- ggplot(speed, aes(y = name, x = median)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - scale_x_continuous(limits = c(0, max(speed$median) * 1.05), expand = c(0, 0)) + - my_theme + - ggtitle("Median time to access field (\u0b5s)") - -p - -## ------------------------------------------------------------------------ -speed <- microbenchmark( - rc$x <- 4, - r6$x <- 4, - r6noclass$x <- 4, - r6noport$x <- 4, - r6noclone$x <- 4, - r6bare$x <- 4, - # r6priv$x <- 4, # Can't set private field directly, - # r6priv_nc_np$x <- 4, # so we'll skip these two - fun_env$x <- 4, - fun_env_nc$x <- 4 -) -speed <- mb_summary(speed) -speed - -## ----echo = FALSE, results = 'hold', fig.width = 8----------------------- -speed$name <- factor(speed$name, rev(levels(speed$name))) - -p <- ggplot(speed, aes(y = name, x = median)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - scale_x_continuous(limits = c(0, max(speed$median) * 1.05), expand = c(0, 0)) + - my_theme + - ggtitle("Median time to set field (\u0b5s)") - -p - -## ------------------------------------------------------------------------ -speed <- microbenchmark( - rc$getx(), - r6$getx(), - r6noclass$getx(), - r6noport$getx(), - r6noclone$getx(), - r6bare$getx(), - r6priv$getx(), - r6priv_bare$getx(), - fun_env$getx(), - fun_env_nc$getx() -) -speed <- mb_summary(speed) -speed - -## ----echo = FALSE, results = 'hold', fig.width = 8----------------------- -speed$name <- factor(speed$name, rev(levels(speed$name))) - -p <- ggplot(speed, aes(y = name, x = median)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - my_theme + - ggtitle("Median time to call method that accesses field (\u0b5s)") - -p - -## ------------------------------------------------------------------------ -RCself <- setRefClass("RCself", - fields = list(x = "numeric"), - methods = list( - initialize = function() .self$x <- 1, - setx = function(n = 2) .self$x <- n - ) -) - -RCnoself <- setRefClass("RCnoself", - fields = list(x = "numeric"), - methods = list( - initialize = function() x <<- 1, - setx = function(n = 2) x <<- n - ) -) - -## ------------------------------------------------------------------------ -R6self <- R6Class("R6self", - portable = FALSE, - public = list( - x = 1, - setx = function(n = 2) self$x <- n - ) -) - -R6noself <- R6Class("R6noself", - portable = FALSE, - public = list( - x = 1, - setx = function(n = 2) x <<- n - ) -) - -## ------------------------------------------------------------------------ -rc_self <- RCself$new() -rc_noself <- RCnoself$new() -r6_self <- R6self$new() -r6_noself <- R6noself$new() - -speed <- microbenchmark( - rc_self$setx(), - rc_noself$setx(), - r6_self$setx(), - r6_noself$setx() -) -speed <- mb_summary(speed) -speed - -## ----echo = FALSE, results = 'hold', fig.width = 8----------------------- -speed$name <- factor(speed$name, rev(levels(speed$name))) - -p <- ggplot(speed, aes(y = name, x = median)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - my_theme + - ggtitle("Assignment to a field using self vs <<- (\u0b5s)") - -p - -## ------------------------------------------------------------------------ -e1 <- new.env(hash = FALSE, parent = emptyenv()) -e2 <- new.env(hash = FALSE, parent = emptyenv()) -e3 <- new.env(hash = FALSE, parent = emptyenv()) - -e1$x <- 1 -e2$x <- 1 -e3$x <- 1 - -class(e2) <- "e2" -class(e3) <- "e3" - -# Define an S3 method for class e3 -`$.e3` <- function(x, name) { - NULL -} - -## ------------------------------------------------------------------------ -speed <- microbenchmark( - e1$x, - e2$x, - e3$x -) -speed <- mb_summary(speed) -speed - -## ------------------------------------------------------------------------ -lst <- list(x = 10) -env <- new.env() -env$x <- 10 - -mb_summary(microbenchmark( - lst = lst$x, - env = env$x, - lst[['x']], - env[['x']] -)) - -## ----eval=FALSE---------------------------------------------------------- -# # Utility functions for calculating sizes -# obj_size <- function(expr, .env = parent.frame()) { -# size_n <- function(n = 1) { -# objs <- lapply(1:n, function(x) eval(expr, .env)) -# as.numeric(do.call(object_size, objs)) -# } -# -# data.frame(one = size_n(1), incremental = size_n(2) - size_n(1)) -# } -# -# obj_sizes <- function(..., .env = parent.frame()) { -# exprs <- as.list(match.call(expand.dots = FALSE)$...) -# names(exprs) <- lapply(1:length(exprs), -# FUN = function(n) { -# name <- names(exprs)[n] -# if (is.null(name) || name == "") paste(deparse(exprs[[n]]), collapse = " ") -# else name -# }) -# -# sizes <- mapply(obj_size, exprs, MoreArgs = list(.env = .env), SIMPLIFY = FALSE) -# do.call(rbind, sizes) -# } - -## ------------------------------------------------------------------------ -sessionInfo() - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Performance.Rmd b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Performance.Rmd deleted file mode 100644 index 086b31c..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Performance.Rmd +++ /dev/null @@ -1,786 +0,0 @@ ---- -title: "R6 and Reference class performance tests" -output: - html_document: - theme: null - css: mystyle.css - toc: yes - fig_retina: false -vignette: > - %\VignetteEngine{knitr::rmarkdown} - %\VignetteIndexEntry{R6 and Reference class performance tests} - %\usepackage[utf8]{inputenc} ---- - -```{r echo = FALSE} -knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 3.9, fig.height = 3.5) - -# Make sure vignette doesn't error on platforms where microbenchmark is not present. -if (requireNamespace("microbenchmark", quietly = TRUE)) { - library(microbenchmark) - - # Only print 3 significant digits - print_microbenchmark <- function (x, unit, order = NULL, ...) { - s <- summary(x, unit = unit) - cat("Unit: ", attr(s, "unit"), "\n", sep = "") - - timing_cols <- c("min", "lq", "median", "uq", "max") - s[timing_cols] <- lapply(s[timing_cols], signif, digits = 3) - s[timing_cols] <- lapply(s[timing_cols], format, big.mark = ",") - - print(s, ..., row.names = FALSE) - } - - assignInNamespace("print.microbenchmark", print_microbenchmark, - "microbenchmark") - -} else { - # Some dummy functions so that the vignette doesn't throw an error. - microbenchmark <- function(...) { - structure(list(), class = "microbenchmark_dummy") - } - - summary.microbenchmark_dummy <- function(object, ...) { - data.frame(expr = "", median = 0) - } -} -``` - -This document compares the memory costs and speed of R's reference classes against R6 classes and simple environments. For must uses, R6 and reference classes have comparable features, but as we'll see, R6 classes are faster and lighter weight. - -This document tests reference classes against R6 classes (in many variations), as well as against very simple reference objects: environments created by functino calls. - -***** - -First we'll load some packages which will be used below: - -```{r eval = FALSE} -library(microbenchmark) -options(microbenchmark.unit = "us") -library(pryr) # For object_size function -library(R6) -``` - -```{r echo = FALSE} -# The previous code block is just for appearances. This code block is the one -# that gets run. The loading of microbenchmark must be conditional because it is -# not available on all platforms. -if (requireNamespace("microbenchmark", quietly = TRUE)) { - library(microbenchmark) -} -options(microbenchmark.unit = "us") -library(pryr) # For object_size function -library(R6) -``` - - -```{r echo=FALSE} -library(ggplot2) -library(scales) - -# Set up ggplot2 theme -my_theme <- theme_bw(base_size = 10) + - theme(axis.title.x = element_blank(), - axis.title.y = element_blank(), - panel.grid.major.y = element_blank(), - panel.grid.minor.y = element_blank() - ) -``` - -***** - -Class definitions -================= - -We'll start by defining a number of classes or class-like entities, using reference classes, R6 classes, and simple environments that are created directly by functions. There are a number of options for R6 that can affect the size of the resulting objects, so we will use a number of variants. These classes will be used for the speed and memory tests that follow. This is a lot of boring code, so you may want to skip ahead to the results. - - -All of these classes have the same basic characteristics: - -* A field named `x` that contains a number. -* An way of initializing the value of `x`. -* A method named `getx` for retrieving the value of `x`. -* A method named `inc` for incrementing the value of `x`. - -The fields and methods are accessed with the `$` operator, so if we have an object named `obj`, we could use `obj$x` or `obj$getx()`. - -## R reference class - -```{r} -RC <- setRefClass("RC", - fields = list(x = "numeric"), - methods = list( - initialize = function(x = 1) .self$x <- x, - getx = function() x, - inc = function(n = 1) x <<- x + n - ) -) -``` - -In reference classes, the binding that points back to the object is named `.self`. Within a method, assignment can be done by using `.self`, as in `.self$x <- 10`, or by using `<<-`, as in `x <<- 10`. - -To create an object, simply call `$new()` on the class: - -```{r} -RC$new() -``` - -## R6 class - -Creating an R6 class is similar to the reference class, except that there's no need to separate the fields and methods, and you can't specify the types of the fields. - -```{r} -R6 <- R6Class("R6", - public = list( - x = NULL, - initialize = function(x = 1) self$x <- x, - getx = function() self$x, - inc = function(n = 1) self$x <- x + n - ) -) -``` - -Whereas reference classes use `.self`, R6 classes use `self` (without the leading period). As with reference classes, objects are instantiated by calling `$new()`: - -```{r} -R6$new() -``` - -An R6 object essentially just a set of environments structured in a particular way. The fields and methods for an R6 object have bindings (that is, they have names) in the *public environment*. There is also have a separate environment which is the *enclosing environment* for methods (they "run in" an environment that contains a binding named `self`, which is simply a reference to the public environment). - - -## R6 class, without class attribute - -By default, a class attribute is added to R6 objects. This attribute adds a slight performance penalty because R will attempt to use S3 dispatch when using `$` on the object. - -It's possible generate objects without the class attribute, by using `class=FALSE`: - -```{r} -R6NoClass <- R6Class("R6NoClass", - class = FALSE, - public = list( - x = NULL, - initialize = function(x = 1) self$x <- x, - getx = function() self$x, - inc = function(n = 1) self$x <- self$x + n - ) -) -``` - -Note that without the class attribute, S3 method dispatch on the objects is not possible. - -## R6 class, non-portable - -By default, R6 objects are *portable*. This means that inheritance can be in classes that are in different packages. However, it also requires the use of `self$` and `private$` to access members, and this incurs a small performance penalty. - -If `portable=FALSE` is used, members can be accessed without using `self$`, and assignment can be done with `<<-`: - -```{r} -R6NonPortable <- R6Class("R6NonPortable", - portable = FALSE, - public = list( - x = NULL, - initialize = function(value = 1) x <<- value, - getx = function() x, - inc = function(n = 1) x <<- x + n - ) -) -``` - - -## R6 class, with `cloneable=FALSE` - -By default, R6 objects have a `clone()` method, which is a fairly large function. If you do not need this feature, you can save some memory by using `cloneable=FALSE`. - -```{r} -R6NonCloneable <- R6Class("R6NonCloneable", - cloneable = FALSE, - public = list( - x = NULL, - initialize = function(x = 1) self$x <- x, - getx = function() self$x, - inc = function(n = 1) self$x <- self$x + n - ) -) -``` - - -## R6 class, without class attribute, non-portable, and non-cloneable - -For comparison, we'll use a an R6 class that is without a class attribute, non-portable, and non-cloneable. This is the most stripped-down we can make an R6 object. - -```{r} -R6Bare <- R6Class("R6Bare", - portable = FALSE, - class = FALSE, - cloneable = FALSE, - public = list( - x = NULL, - initialize = function(value = 1) x <<- value, - getx = function() x, - inc = function(n = 1) x <<- x + n - ) -) -``` - - -## R6 class, with public and private members - -This variant has public and private members. - -```{r} -R6Private <- R6Class("R6Private", - private = list(x = NULL), - public = list( - initialize = function(x = 1) private$x <- x, - getx = function() private$x, - inc = function(n = 1) private$x <- private$x + n - ) -) -``` - -Instead of a single `self` object which refers to all items in an object, these objects have `self` (which refers to the public items) and `private`. - -```{r} -R6Private$new() -``` - - -## R6 class, with public and private, no class attribute, non-portable, and non-cloneable - -For comparison, we'll add a version that is without a class attribute, non-portable, and non-cloneable. - -```{r} -R6PrivateBare <- R6Class("R6PrivateBare", - portable = FALSE, - class = FALSE, - cloneable = FALSE, - private = list(x = NULL), - public = list( - initialize = function(x = 1) private$x <- x, - getx = function() x, - inc = function(n = 1) x <<- x + n - ) -) -``` - - -## Environment created by a function call, with class attribute - -In R, environments are passed by reference. A simple way to create an object that's passed by reference is to use the environment created by the invocation of a function. The function below captures that environment, attaches a class to it, and returns it: - -```{r} -FunctionEnvClass <- function(x = 1) { - inc <- function(n = 1) x <<- x + n - getx <- function() x - self <- environment() - class(self) <- "FunctionEnvClass" - self -} -``` - -Even though `x` isn't declared in the function body, it gets captured because it's an argument to the function. - -```{r} -ls(FunctionEnvClass()) -``` - -Objects created this way are very similar to those created by `R6` generator we created above. - - -## Environment created by a function call, without class attribute - -We can make an even simpler type of reference object to the previous one, by not having a a class attribute, and not having `self` object: - -```{r} -FunctionEnvNoClass <- function(x = 1) { - inc <- function(n = 1) x <<- x + n - getx <- function() x - environment() -} -``` - -This is simply an environment with some objects in it. - -```{r} -ls(FunctionEnvNoClass()) -``` - -***** - -Tests -===== - -For all the timings using `microbenchmark()`, the results are reported in microseconds, and the most useful value is probably the median column. - -## Memory footprint - -```{r echo = FALSE} -# Utility functions for calculating sizes -obj_size <- function(expr, .env = parent.frame()) { - size_n <- function(n = 1) { - objs <- lapply(1:n, function(x) eval(expr, .env)) - as.numeric(do.call(object_size, objs)) - } - - data.frame(one = size_n(1), incremental = size_n(2) - size_n(1)) -} - -obj_sizes <- function(..., .env = parent.frame()) { - exprs <- as.list(match.call(expand.dots = FALSE)$...) - names(exprs) <- lapply(1:length(exprs), - FUN = function(n) { - name <- names(exprs)[n] - if (is.null(name) || name == "") paste(deparse(exprs[[n]]), collapse = " ") - else name - }) - - sizes <- mapply(obj_size, exprs, MoreArgs = list(.env = .env), SIMPLIFY = FALSE) - do.call(rbind, sizes) -} -``` - - -How much memory does a single instance of each object take, and how much memory does each additional object take? We'll use the functions `obj_size` and `obj_sizes` (shown at the bottom of this document) to calculate the sizes. - -Sizes of each type of object, in bytes: - -```{r} -sizes <- obj_sizes( - RC$new(), - R6$new(), - R6NoClass$new(), - R6NonPortable$new(), - R6NonCloneable$new(), - R6Bare$new(), - R6Private$new(), - R6PrivateBare$new(), - FunctionEnvClass(), - FunctionEnvNoClass() -) -sizes -``` - -The results are plotted below. Note that the plots have very different x scales. - -```{r echo = FALSE, results = 'hold'} -objnames <- c( - "RC", "R6", "R6NoClass", "R6NonPortable", "R6NonCloneable", - "R6Bare", "R6Private", "R6PrivateBare", "FunctionEnvClass", - "FunctionEnvNoClass" -) - -obj_labels <- objnames -obj_labels[1] <- "RC (off chart)" - -sizes$name <- factor(objnames, levels = rev(objnames)) - -ggplot(sizes, aes(y = name, x = one)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - scale_x_continuous(limits = c(0, max(sizes$one[-1]) * 1.5), - expand = c(0, 0), oob = rescale_none) + - scale_y_discrete( - breaks = sizes$name, - labels = obj_labels) + - my_theme + - ggtitle("First object") - -ggplot(sizes, aes(y = name, x = incremental)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - scale_x_continuous(limits = c(0, max(sizes$incremental) * 1.05), - expand = c(0, 0)) + - geom_point(size = 2) + - my_theme + - ggtitle("Additional objects") -``` - -Some preliminary observations about the first instance of various classes: Using a reference class consumes a large amount of memory. For R6 objects, the option with the largest impact is `cloneable`: not having the `clone()` method saves around 40 kB of memory. - -For subsequent instances of these classes, there isn't nearly as much difference between the different kinds. - - -It appeared that using a reference class takes up a huge amount of memory, but much of that is shared between reference classes. Adding an object from a different reference class doesn't require much more memory --- around 38KB: - -```{r} -RC2 <- setRefClass("RC2", - fields = list(x = "numeric"), - methods = list( - initialize = function(x = 2) .self$x <<- x, - inc = function(n = 2) x <<- x * n - ) -) - -# Calcualte the size of a new RC2 object, over and above an RC object -as.numeric(object_size(RC$new(), RC2$new()) - object_size(RC$new())) -``` - -## Object instantiation speed - -How much time does it take to create one of these objects? This shows the median time, in microseconds: - -```{r} -# Function to extract the medians from microbenchmark results -mb_summary <- function(x) { - res <- summary(x, unit="us") - data.frame(name = res$expr, median = res$median) -} - -speed <- microbenchmark( - RC$new(), - R6$new(), - R6NoClass$new(), - R6NonPortable$new(), - R6NonCloneable$new(), - R6Bare$new(), - R6Private$new(), - R6PrivateBare$new(), - FunctionEnvClass(), - FunctionEnvNoClass() -) -speed <- mb_summary(speed) -speed -``` - -The plot below shows the median instantiation time. - -```{r echo = FALSE, results = 'hold', fig.width = 8} -speed$name <- factor(speed$name, rev(levels(speed$name))) - -p <- ggplot(speed, aes(y = name, x = median)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - scale_x_continuous(limits = c(0, max(speed$median) * 1.05), expand = c(0, 0)) + - my_theme + - ggtitle("Median time to instantiate object (\u0b5s)") - -p -``` - -Reference classes are much slower to instantiate than the other types of classes. Instantiating R6 objects is roughly 5 times faster. Creating an environment with a simple function call is another 20-30 times faster. - - -## Field access speed - -How much time does it take to access a field in an object? First we'll make some objects: - -```{r} -rc <- RC$new() -r6 <- R6$new() -r6noclass <- R6NoClass$new() -r6noport <- R6NonPortable$new() -r6noclone <- R6NonCloneable$new() -r6bare <- R6Bare$new() -r6priv <- R6Private$new() -r6priv_bare <- R6PrivateBare$new() -fun_env <- FunctionEnvClass() -fun_env_nc <- FunctionEnvNoClass() -``` - -And then get a value from these objects: - -```{r} -speed <- microbenchmark( - rc$x, - r6$x, - r6noclass$x, - r6noport$x, - r6noclone$x, - r6bare$x, - r6priv$x, - r6priv_bare$x, - fun_env$x, - fun_env_nc$x -) -speed <- mb_summary(speed) -speed -``` - - -```{r echo = FALSE, results = 'hold', fig.width = 8} -speed$name <- factor(speed$name, rev(levels(speed$name))) - -p <- ggplot(speed, aes(y = name, x = median)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - scale_x_continuous(limits = c(0, max(speed$median) * 1.05), expand = c(0, 0)) + - my_theme + - ggtitle("Median time to access field (\u0b5s)") - -p -``` - -Accessing the field of a reference class is much slower than the other methods. - -There's also an obvious pattern where accessing the field of an environment (created by R6 or a function call) is slower when there is a class attribute. This is because, for the objects that have a class attribute, R attempts to look up an S3 method for `$`, and this lookup has a performance penalty. We'll see more about this below. - - -## Field setting speed - -How much time does it take to set the value of a field in an object? - -```{r} -speed <- microbenchmark( - rc$x <- 4, - r6$x <- 4, - r6noclass$x <- 4, - r6noport$x <- 4, - r6noclone$x <- 4, - r6bare$x <- 4, - # r6priv$x <- 4, # Can't set private field directly, - # r6priv_nc_np$x <- 4, # so we'll skip these two - fun_env$x <- 4, - fun_env_nc$x <- 4 -) -speed <- mb_summary(speed) -speed -``` - -```{r echo = FALSE, results = 'hold', fig.width = 8} -speed$name <- factor(speed$name, rev(levels(speed$name))) - -p <- ggplot(speed, aes(y = name, x = median)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - scale_x_continuous(limits = c(0, max(speed$median) * 1.05), expand = c(0, 0)) + - my_theme + - ggtitle("Median time to set field (\u0b5s)") - -p -``` - -Reference classes are significantly slower than the others, again. In this case, there's additional overhead due to type-checking the value. - -Once more, the no-class objects are significantly faster than the others, again probably due to attempted S3 dispatch on the `` `$<-` `` function. - -## Speed of method call that accesses a field - -How much overhead is there when calling a method from one of these objects? All of these `getx()` methods simply return the value of `x` in the object. When necessary, this method uses `self$x` (for R6 classes, when `portable=TRUE`), and in others, it just uses `x` (when `portable=FALSE`, and in reference classes). - -```{r} -speed <- microbenchmark( - rc$getx(), - r6$getx(), - r6noclass$getx(), - r6noport$getx(), - r6noclone$getx(), - r6bare$getx(), - r6priv$getx(), - r6priv_bare$getx(), - fun_env$getx(), - fun_env_nc$getx() -) -speed <- mb_summary(speed) -speed -``` - -```{r echo = FALSE, results = 'hold', fig.width = 8} -speed$name <- factor(speed$name, rev(levels(speed$name))) - -p <- ggplot(speed, aes(y = name, x = median)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - my_theme + - ggtitle("Median time to call method that accesses field (\u0b5s)") - -p -``` - -The reference class is the slowest. - -`r6` is also somewhat slower than the others. There are two reasons for this: first, it uses `self$x` which adds some time, and second, it has a class attribute, which slows down the access of both `r6$getx` and `self$x`. - -One might expect `r6priv` to be the same speed as `r6`, but it is faster. Although accessing `r6priv$getx` is slow because `r6priv` has a class attribute, accessing `private$x` is faster because it does not have a class attribute. - -The objects which can access `x` directly (without `self` or `private`) and which lack a class attribute are the fastest. - -## Assignment using `self$x <-` vs. `x <<-` - -With reference classes, you can modify fields using the `<<-` operator, or by using the `.self` object. For example, compare the `setx()` methods of these two classes: - -```{r} -RCself <- setRefClass("RCself", - fields = list(x = "numeric"), - methods = list( - initialize = function() .self$x <- 1, - setx = function(n = 2) .self$x <- n - ) -) - -RCnoself <- setRefClass("RCnoself", - fields = list(x = "numeric"), - methods = list( - initialize = function() x <<- 1, - setx = function(n = 2) x <<- n - ) -) -``` - -Non-portable R6 classes are similar, except they use `self` instead of `.self`. - -```{r} -R6self <- R6Class("R6self", - portable = FALSE, - public = list( - x = 1, - setx = function(n = 2) self$x <- n - ) -) - -R6noself <- R6Class("R6noself", - portable = FALSE, - public = list( - x = 1, - setx = function(n = 2) x <<- n - ) -) -``` - - -```{r} -rc_self <- RCself$new() -rc_noself <- RCnoself$new() -r6_self <- R6self$new() -r6_noself <- R6noself$new() - -speed <- microbenchmark( - rc_self$setx(), - rc_noself$setx(), - r6_self$setx(), - r6_noself$setx() -) -speed <- mb_summary(speed) -speed -``` - -```{r echo = FALSE, results = 'hold', fig.width = 8} -speed$name <- factor(speed$name, rev(levels(speed$name))) - -p <- ggplot(speed, aes(y = name, x = median)) + - geom_segment(aes(yend = name), xend = 0, colour = "gray80") + - geom_point(size = 2) + - my_theme + - ggtitle("Assignment to a field using self vs <<- (\u0b5s)") - -p -``` - -For both reference and non-portable R6 classes, assignment using `.self$x <-` is somewhat slower than using `x <<-`. - -Bear in mind that, by default, R6 classes are portable, and can't use assignment with `x <<-`. - -## Overhead from using `$` on objects with a class attribute - -There is some overhead when using `$` on an object that has a class attribute. In the test below, we'll create three different kinds of objects: - -1. An environment with no class attribute. -1. An environment with a class `"e2"`, but without a `$.e2` S3 method. -1. An environment with a class `"e3"`, which has a `$.e3` S3 method that simply returns `NULL`. - -Each one of these environments will contain an object `x`. - -```{r} -e1 <- new.env(hash = FALSE, parent = emptyenv()) -e2 <- new.env(hash = FALSE, parent = emptyenv()) -e3 <- new.env(hash = FALSE, parent = emptyenv()) - -e1$x <- 1 -e2$x <- 1 -e3$x <- 1 - -class(e2) <- "e2" -class(e3) <- "e3" - -# Define an S3 method for class e3 -`$.e3` <- function(x, name) { - NULL -} -``` - -Now we can run timing tests for calling `$` on each type of object. Note that for the `e3` object, the `$` function does nothing --- it simply returns `NULL`. - -```{r} -speed <- microbenchmark( - e1$x, - e2$x, - e3$x -) -speed <- mb_summary(speed) -speed -``` - -Using `$` on `e2` and `e3` is much slower than on `e1`. This is because `e2` and `e3` have a class attribute. Even though there's no `$` method defined for `e2`, doing `e2$x` still about 6 times slower than `e1$x`, simply because R looks for an appropriate S3 method. - -`e3$x` is slightly faster than `e2$x`; this is probably because the `$.e3` function doesn't actually do anything other than return NULL. - -If an object has a class attribute, R will attempt to look for a method every time `$` is called. This can slow things down considerably, if `$` is used often. - -## Lists vs. environments, and `$` vs. `[[` - -Lists could also be used for creating classes (albeit not with reference semantics). How much time does it take to access items using `$` for lists vs. environments? We'll also compare using `obj$x` to `obj[['x']]`. - -```{r} -lst <- list(x = 10) -env <- new.env() -env$x <- 10 - -mb_summary(microbenchmark( - lst = lst$x, - env = env$x, - lst[['x']], - env[['x']] -)) -``` - -Performance is comparable across environments and lists. - -The `[[` operator is slightly faster than `$`, probably because it doesn't need to convert the unevaluated symbol to a string. - -***** - -Wrap-up -======= - -R6 objects take less memory and are significantly faster than R's reference class objects, and they also have some options that provide for even more speed. - -In these tests, the biggest speedup for R6 classes comes from not using a class attribute; this speeds up the use of `$`. Non-portable R6 classes can also access fields without `$` at all, which provides another modest speed boost. In most cases, these speed increases are negligible -- they are on the order of microseconds and will be noticeable only when tens or even hundreds of thousands of class member accesses are performed. - - -***** - -Appendix -======== - -## Functions for calculating object sizes - -```{r eval=FALSE} -# Utility functions for calculating sizes -obj_size <- function(expr, .env = parent.frame()) { - size_n <- function(n = 1) { - objs <- lapply(1:n, function(x) eval(expr, .env)) - as.numeric(do.call(object_size, objs)) - } - - data.frame(one = size_n(1), incremental = size_n(2) - size_n(1)) -} - -obj_sizes <- function(..., .env = parent.frame()) { - exprs <- as.list(match.call(expand.dots = FALSE)$...) - names(exprs) <- lapply(1:length(exprs), - FUN = function(n) { - name <- names(exprs)[n] - if (is.null(name) || name == "") paste(deparse(exprs[[n]]), collapse = " ") - else name - }) - - sizes <- mapply(obj_size, exprs, MoreArgs = list(.env = .env), SIMPLIFY = FALSE) - do.call(rbind, sizes) -} -``` - - -## System information - -```{r} -sessionInfo() -``` diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Performance.html b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Performance.html deleted file mode 100644 index 860a8ff..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Performance.html +++ /dev/null @@ -1,649 +0,0 @@ - - - - - - - - - - - - - - -R6 and Reference class performance tests - - - - - - - - - - - - - - - - - - - -

R6 and Reference class performance tests

- - - - -

This document compares the memory costs and speed of R’s reference classes against R6 classes and simple environments. For must uses, R6 and reference classes have comparable features, but as we’ll see, R6 classes are faster and lighter weight.

-

This document tests reference classes against R6 classes (in many variations), as well as against very simple reference objects: environments created by functino calls.

-
-

First we’ll load some packages which will be used below:

-
library(microbenchmark)
-options(microbenchmark.unit = "us")
-library(pryr)  # For object_size function
-library(R6)
-
-
-

Class definitions

-

We’ll start by defining a number of classes or class-like entities, using reference classes, R6 classes, and simple environments that are created directly by functions. There are a number of options for R6 that can affect the size of the resulting objects, so we will use a number of variants. These classes will be used for the speed and memory tests that follow. This is a lot of boring code, so you may want to skip ahead to the results.

-

All of these classes have the same basic characteristics:

-
    -
  • A field named x that contains a number.
  • -
  • An way of initializing the value of x.
  • -
  • A method named getx for retrieving the value of x.
  • -
  • A method named inc for incrementing the value of x.
  • -
-

The fields and methods are accessed with the $ operator, so if we have an object named obj, we could use obj$x or obj$getx().

-
-

R reference class

-
RC <- setRefClass("RC",
-  fields = list(x = "numeric"),
-  methods = list(
-    initialize = function(x = 1) .self$x <- x,
-    getx = function() x,
-    inc = function(n = 1) x <<- x + n
-  )
-)
-

In reference classes, the binding that points back to the object is named .self. Within a method, assignment can be done by using .self, as in .self$x <- 10, or by using <<-, as in x <<- 10.

-

To create an object, simply call $new() on the class:

-
RC$new()
-#> Reference class object of class "RC"
-#> Field "x":
-#> [1] 1
-
-
-

R6 class

-

Creating an R6 class is similar to the reference class, except that there’s no need to separate the fields and methods, and you can’t specify the types of the fields.

-
R6 <- R6Class("R6",
-  public = list(
-    x = NULL,
-    initialize = function(x = 1) self$x <- x,
-    getx = function() self$x,
-    inc = function(n = 1) self$x <- x + n
-  )
-)
-

Whereas reference classes use .self, R6 classes use self (without the leading period). As with reference classes, objects are instantiated by calling $new():

-
R6$new()
-#> <R6>
-#>   Public:
-#>     clone: function (deep = FALSE) 
-#>     getx: function () 
-#>     inc: function (n = 1) 
-#>     initialize: function (x = 1) 
-#>     x: 1
-

An R6 object essentially just a set of environments structured in a particular way. The fields and methods for an R6 object have bindings (that is, they have names) in the public environment. There is also have a separate environment which is the enclosing environment for methods (they “run in” an environment that contains a binding named self, which is simply a reference to the public environment).

-
-
-

R6 class, without class attribute

-

By default, a class attribute is added to R6 objects. This attribute adds a slight performance penalty because R will attempt to use S3 dispatch when using $ on the object.

-

It’s possible generate objects without the class attribute, by using class=FALSE:

-
R6NoClass <- R6Class("R6NoClass",
-  class = FALSE,
-  public = list(
-    x = NULL,
-    initialize = function(x = 1) self$x <- x,
-    getx = function() self$x,
-    inc = function(n = 1) self$x <- self$x + n
-  )
-)
-

Note that without the class attribute, S3 method dispatch on the objects is not possible.

-
-
-

R6 class, non-portable

-

By default, R6 objects are portable. This means that inheritance can be in classes that are in different packages. However, it also requires the use of self$ and private$ to access members, and this incurs a small performance penalty.

-

If portable=FALSE is used, members can be accessed without using self$, and assignment can be done with <<-:

-
R6NonPortable <- R6Class("R6NonPortable",
-  portable = FALSE,
-  public = list(
-    x = NULL,
-    initialize = function(value = 1) x <<- value,
-    getx = function() x,
-    inc = function(n = 1) x <<- x + n
-  )
-)
-
-
-

R6 class, with cloneable=FALSE

-

By default, R6 objects have a clone() method, which is a fairly large function. If you do not need this feature, you can save some memory by using cloneable=FALSE.

-
R6NonCloneable <- R6Class("R6NonCloneable",
-  cloneable = FALSE,
-  public = list(
-    x = NULL,
-    initialize = function(x = 1) self$x <- x,
-    getx = function() self$x,
-    inc = function(n = 1) self$x <- self$x + n
-  )
-)
-
-
-

R6 class, without class attribute, non-portable, and non-cloneable

-

For comparison, we’ll use a an R6 class that is without a class attribute, non-portable, and non-cloneable. This is the most stripped-down we can make an R6 object.

-
R6Bare <- R6Class("R6Bare",
-  portable = FALSE,
-  class = FALSE,
-  cloneable = FALSE,
-  public = list(
-    x = NULL,
-    initialize = function(value = 1) x <<- value,
-    getx = function() x,
-    inc = function(n = 1) x <<- x + n
-  )
-)
-
-
-

R6 class, with public and private members

-

This variant has public and private members.

-
R6Private <- R6Class("R6Private",
-  private = list(x = NULL),
-  public = list(
-    initialize = function(x = 1) private$x <- x,
-    getx = function() private$x,
-    inc = function(n = 1) private$x <- private$x + n
-  )
-)
-

Instead of a single self object which refers to all items in an object, these objects have self (which refers to the public items) and private.

-
R6Private$new()
-#> <R6Private>
-#>   Public:
-#>     clone: function (deep = FALSE) 
-#>     getx: function () 
-#>     inc: function (n = 1) 
-#>     initialize: function (x = 1) 
-#>   Private:
-#>     x: 1
-
-
-

R6 class, with public and private, no class attribute, non-portable, and non-cloneable

-

For comparison, we’ll add a version that is without a class attribute, non-portable, and non-cloneable.

-
R6PrivateBare <- R6Class("R6PrivateBare",
-  portable = FALSE,
-  class = FALSE,
-  cloneable = FALSE,
-  private = list(x = NULL),
-  public = list(
-    initialize = function(x = 1) private$x <- x,
-    getx = function() x,
-    inc = function(n = 1) x <<- x + n
-  )
-)
-
-
-

Environment created by a function call, with class attribute

-

In R, environments are passed by reference. A simple way to create an object that’s passed by reference is to use the environment created by the invocation of a function. The function below captures that environment, attaches a class to it, and returns it:

-
FunctionEnvClass <- function(x = 1) {
-  inc <- function(n = 1) x <<- x + n
-  getx <- function() x
-  self <- environment()
-  class(self) <- "FunctionEnvClass"
-  self
-}
-

Even though x isn’t declared in the function body, it gets captured because it’s an argument to the function.

-
ls(FunctionEnvClass())
-#> [1] "getx" "inc"  "self" "x"
-

Objects created this way are very similar to those created by R6 generator we created above.

-
-
-

Environment created by a function call, without class attribute

-

We can make an even simpler type of reference object to the previous one, by not having a a class attribute, and not having self object:

-
FunctionEnvNoClass <- function(x = 1) {
-  inc <- function(n = 1) x <<- x + n
-  getx <- function() x
-  environment()
-}
-

This is simply an environment with some objects in it.

-
ls(FunctionEnvNoClass())
-#> [1] "getx" "inc"  "x"
-
-
-
-
-

Tests

-

For all the timings using microbenchmark(), the results are reported in microseconds, and the most useful value is probably the median column.

-
-

Memory footprint

-

How much memory does a single instance of each object take, and how much memory does each additional object take? We’ll use the functions obj_size and obj_sizes (shown at the bottom of this document) to calculate the sizes.

-

Sizes of each type of object, in bytes:

-
sizes <- obj_sizes(
-  RC$new(),
-  R6$new(),
-  R6NoClass$new(),
-  R6NonPortable$new(),
-  R6NonCloneable$new(),
-  R6Bare$new(),
-  R6Private$new(),
-  R6PrivateBare$new(),
-  FunctionEnvClass(),
-  FunctionEnvNoClass()
-)
-sizes
-#>                         one incremental
-#> RC$new()             555688        1368
-#> R6$new()              60776        1008
-#> R6NoClass$new()       61480         896
-#> R6NonPortable$new()   60368         952
-#> R6NonCloneable$new()  13704         896
-#> R6Bare$new()          12896         728
-#> R6Private$new()       61680        1120
-#> R6PrivateBare$new()   13904         840
-#> FunctionEnvClass()    12816         624
-#> FunctionEnvNoClass()  11392         512
-

The results are plotted below. Note that the plots have very different x scales.

-

-

Some preliminary observations about the first instance of various classes: Using a reference class consumes a large amount of memory. For R6 objects, the option with the largest impact is cloneable: not having the clone() method saves around 40 kB of memory.

-

For subsequent instances of these classes, there isn’t nearly as much difference between the different kinds.

-

It appeared that using a reference class takes up a huge amount of memory, but much of that is shared between reference classes. Adding an object from a different reference class doesn’t require much more memory — around 38KB:

-
RC2 <- setRefClass("RC2",
-  fields = list(x = "numeric"),
-  methods = list(
-    initialize = function(x = 2) .self$x <<- x,
-    inc = function(n = 2) x <<- x * n
-  )
-)
-
-# Calcualte the size of a new RC2 object, over and above an RC object
-as.numeric(object_size(RC$new(), RC2$new()) - object_size(RC$new()))
-#> [1] 37176
-
-
-

Object instantiation speed

-

How much time does it take to create one of these objects? This shows the median time, in microseconds:

-
# Function to extract the medians from microbenchmark results
-mb_summary <- function(x) {
-  res <- summary(x, unit="us")
-  data.frame(name = res$expr, median = res$median)
-}
-
-speed <- microbenchmark(
-  RC$new(),
-  R6$new(),
-  R6NoClass$new(),
-  R6NonPortable$new(),
-  R6NonCloneable$new(),
-  R6Bare$new(),
-  R6Private$new(),
-  R6PrivateBare$new(),
-  FunctionEnvClass(),
-  FunctionEnvNoClass()
-)
-speed <- mb_summary(speed)
-speed
-#>                    name   median
-#> 1              RC$new() 220.1525
-#> 2              R6$new()  39.1770
-#> 3       R6NoClass$new()  36.3810
-#> 4   R6NonPortable$new()  36.6365
-#> 5  R6NonCloneable$new()  37.3490
-#> 6          R6Bare$new()  33.4570
-#> 7       R6Private$new()  52.5565
-#> 8   R6PrivateBare$new()  45.6435
-#> 9    FunctionEnvClass()   1.9740
-#> 10 FunctionEnvNoClass()   1.2335
-

The plot below shows the median instantiation time.

-

-

Reference classes are much slower to instantiate than the other types of classes. Instantiating R6 objects is roughly 5 times faster. Creating an environment with a simple function call is another 20-30 times faster.

-
-
-

Field access speed

-

How much time does it take to access a field in an object? First we’ll make some objects:

-
rc           <- RC$new()
-r6           <- R6$new()
-r6noclass    <- R6NoClass$new()
-r6noport     <- R6NonPortable$new()
-r6noclone    <- R6NonCloneable$new()
-r6bare       <- R6Bare$new()
-r6priv       <- R6Private$new()
-r6priv_bare  <- R6PrivateBare$new()
-fun_env      <- FunctionEnvClass()
-fun_env_nc   <- FunctionEnvNoClass()
-

And then get a value from these objects:

-
speed <- microbenchmark(
-  rc$x,
-  r6$x,
-  r6noclass$x,
-  r6noport$x,
-  r6noclone$x,
-  r6bare$x,
-  r6priv$x,
-  r6priv_bare$x,
-  fun_env$x,
-  fun_env_nc$x
-)
-speed <- mb_summary(speed)
-speed
-#>             name median
-#> 1           rc$x 6.4705
-#> 2           r6$x 1.0975
-#> 3    r6noclass$x 0.2555
-#> 4     r6noport$x 1.2270
-#> 5    r6noclone$x 1.1915
-#> 6       r6bare$x 0.2565
-#> 7       r6priv$x 1.2145
-#> 8  r6priv_bare$x 0.2650
-#> 9      fun_env$x 0.9770
-#> 10  fun_env_nc$x 0.2710
-

-

Accessing the field of a reference class is much slower than the other methods.

-

There’s also an obvious pattern where accessing the field of an environment (created by R6 or a function call) is slower when there is a class attribute. This is because, for the objects that have a class attribute, R attempts to look up an S3 method for $, and this lookup has a performance penalty. We’ll see more about this below.

-
-
-

Field setting speed

-

How much time does it take to set the value of a field in an object?

-
speed <- microbenchmark(
-  rc$x <- 4,
-  r6$x <- 4,
-  r6noclass$x <- 4,
-  r6noport$x <- 4,
-  r6noclone$x <- 4,
-  r6bare$x <- 4,
-  # r6priv$x <- 4,         # Can't set private field directly,
-  # r6priv_nc_np$x <- 4,   # so we'll skip these two
-  fun_env$x <- 4,
-  fun_env_nc$x <- 4
-)
-speed <- mb_summary(speed)
-speed
-#>                name  median
-#> 1         rc$x <- 4 30.7685
-#> 2         r6$x <- 4  1.7340
-#> 3  r6noclass$x <- 4  0.7465
-#> 4   r6noport$x <- 4  1.8975
-#> 5  r6noclone$x <- 4  1.8760
-#> 6     r6bare$x <- 4  0.7095
-#> 7    fun_env$x <- 4  1.6460
-#> 8 fun_env_nc$x <- 4  0.7305
-

-

Reference classes are significantly slower than the others, again. In this case, there’s additional overhead due to type-checking the value.

-

Once more, the no-class objects are significantly faster than the others, again probably due to attempted S3 dispatch on the `$<-` function.

-
-
-

Speed of method call that accesses a field

-

How much overhead is there when calling a method from one of these objects? All of these getx() methods simply return the value of x in the object. When necessary, this method uses self$x (for R6 classes, when portable=TRUE), and in others, it just uses x (when portable=FALSE, and in reference classes).

-
speed <- microbenchmark(
-  rc$getx(),
-  r6$getx(),
-  r6noclass$getx(),
-  r6noport$getx(),
-  r6noclone$getx(),
-  r6bare$getx(),
-  r6priv$getx(),
-  r6priv_bare$getx(),
-  fun_env$getx(),
-  fun_env_nc$getx()
-)
-speed <- mb_summary(speed)
-speed
-#>                  name median
-#> 1           rc$getx() 6.7705
-#> 2           r6$getx() 2.4550
-#> 3    r6noclass$getx() 0.5940
-#> 4     r6noport$getx() 1.4190
-#> 5    r6noclone$getx() 2.5665
-#> 6       r6bare$getx() 0.4000
-#> 7       r6priv$getx() 1.6015
-#> 8  r6priv_bare$getx() 0.4070
-#> 9      fun_env$getx() 1.2165
-#> 10  fun_env_nc$getx() 0.4015
-

-

The reference class is the slowest.

-

r6 is also somewhat slower than the others. There are two reasons for this: first, it uses self$x which adds some time, and second, it has a class attribute, which slows down the access of both r6$getx and self$x.

-

One might expect r6priv to be the same speed as r6, but it is faster. Although accessing r6priv$getx is slow because r6priv has a class attribute, accessing private$x is faster because it does not have a class attribute.

-

The objects which can access x directly (without self or private) and which lack a class attribute are the fastest.

-
-
-

Assignment using self$x <- vs. x <<-

-

With reference classes, you can modify fields using the <<- operator, or by using the .self object. For example, compare the setx() methods of these two classes:

-
RCself <- setRefClass("RCself",
-  fields = list(x = "numeric"),
-  methods = list(
-    initialize = function() .self$x <- 1,
-    setx = function(n = 2) .self$x <- n
-  )
-)
-
-RCnoself <- setRefClass("RCnoself",
-  fields = list(x = "numeric"),
-  methods = list(
-    initialize = function() x <<- 1,
-    setx = function(n = 2) x <<- n
-  )
-)
-

Non-portable R6 classes are similar, except they use self instead of .self.

-
R6self <- R6Class("R6self",
-  portable = FALSE,
-  public = list(
-    x = 1,
-    setx = function(n = 2) self$x <- n
-  )
-)
-
-R6noself <- R6Class("R6noself",
-  portable = FALSE,
-  public = list(
-    x = 1,
-    setx = function(n = 2) x <<- n
-  )
-)
-
rc_self   <- RCself$new()
-rc_noself <- RCnoself$new()
-r6_self   <- R6self$new()
-r6_noself <- R6noself$new()
-
-speed <- microbenchmark(
-  rc_self$setx(),
-  rc_noself$setx(),
-  r6_self$setx(),
-  r6_noself$setx()
-)
-speed <- mb_summary(speed)
-speed
-#>               name  median
-#> 1   rc_self$setx() 36.4870
-#> 2 rc_noself$setx() 22.4990
-#> 3   r6_self$setx()  4.0360
-#> 4 r6_noself$setx()  1.8445
-

-

For both reference and non-portable R6 classes, assignment using .self$x <- is somewhat slower than using x <<-.

-

Bear in mind that, by default, R6 classes are portable, and can’t use assignment with x <<-.

-
-
-

Overhead from using $ on objects with a class attribute

-

There is some overhead when using $ on an object that has a class attribute. In the test below, we’ll create three different kinds of objects:

-
    -
  1. An environment with no class attribute.
  2. -
  3. An environment with a class "e2", but without a $.e2 S3 method.
  4. -
  5. An environment with a class "e3", which has a $.e3 S3 method that simply returns NULL.
  6. -
-

Each one of these environments will contain an object x.

-
e1 <- new.env(hash = FALSE, parent = emptyenv())
-e2 <- new.env(hash = FALSE, parent = emptyenv())
-e3 <- new.env(hash = FALSE, parent = emptyenv())
-
-e1$x <- 1
-e2$x <- 1
-e3$x <- 1
-
-class(e2) <- "e2"
-class(e3) <- "e3"
-
-# Define an S3 method for class e3
-`$.e3` <- function(x, name) {
-  NULL
-}
-

Now we can run timing tests for calling $ on each type of object. Note that for the e3 object, the $ function does nothing — it simply returns NULL.

-
speed <- microbenchmark(
-  e1$x,
-  e2$x,
-  e3$x
-)
-speed <- mb_summary(speed)
-speed
-#>   name median
-#> 1 e1$x 0.2230
-#> 2 e2$x 0.8745
-#> 3 e3$x 0.7585
-

Using $ on e2 and e3 is much slower than on e1. This is because e2 and e3 have a class attribute. Even though there’s no $ method defined for e2, doing e2$x still about 6 times slower than e1$x, simply because R looks for an appropriate S3 method.

-

e3$x is slightly faster than e2$x; this is probably because the $.e3 function doesn’t actually do anything other than return NULL.

-

If an object has a class attribute, R will attempt to look for a method every time $ is called. This can slow things down considerably, if $ is used often.

-
-
-

Lists vs. environments, and $ vs. [[

-

Lists could also be used for creating classes (albeit not with reference semantics). How much time does it take to access items using $ for lists vs. environments? We’ll also compare using obj$x to obj[['x']].

-
lst <- list(x = 10)
-env <- new.env()
-env$x <- 10
-
-mb_summary(microbenchmark(
-  lst = lst$x,
-  env = env$x,
-  lst[['x']],
-  env[['x']]
-))
-#>         name median
-#> 1        lst 0.2065
-#> 2        env 0.2110
-#> 3 lst[["x"]] 0.1575
-#> 4 env[["x"]] 0.1550
-

Performance is comparable across environments and lists.

-

The [[ operator is slightly faster than $, probably because it doesn’t need to convert the unevaluated symbol to a string.

-
-
-
-
-

Wrap-up

-

R6 objects take less memory and are significantly faster than R’s reference class objects, and they also have some options that provide for even more speed.

-

In these tests, the biggest speedup for R6 classes comes from not using a class attribute; this speeds up the use of $. Non-portable R6 classes can also access fields without $ at all, which provides another modest speed boost. In most cases, these speed increases are negligible – they are on the order of microseconds and will be noticeable only when tens or even hundreds of thousands of class member accesses are performed.

-
-
-
-

Appendix

-
-

Functions for calculating object sizes

-
# Utility functions for calculating sizes
-obj_size <- function(expr, .env = parent.frame()) {
-  size_n <- function(n = 1) {
-    objs <- lapply(1:n, function(x) eval(expr, .env))
-    as.numeric(do.call(object_size, objs))
-  }
-
-  data.frame(one = size_n(1), incremental = size_n(2) - size_n(1))
-}
-
-obj_sizes <- function(..., .env = parent.frame()) {
-  exprs <- as.list(match.call(expand.dots = FALSE)$...)
-  names(exprs) <- lapply(1:length(exprs),
-    FUN = function(n) {
-      name <- names(exprs)[n]
-      if (is.null(name) || name == "") paste(deparse(exprs[[n]]), collapse = " ")
-      else name
-    })
-
-  sizes <- mapply(obj_size, exprs, MoreArgs = list(.env = .env), SIMPLIFY = FALSE)
-  do.call(rbind, sizes)
-}
-
-
-

System information

-
sessionInfo()
-#> R version 3.4.0 (2017-04-21)
-#> Platform: x86_64-apple-darwin15.6.0 (64-bit)
-#> Running under: macOS Sierra 10.12.5
-#> 
-#> Matrix products: default
-#> BLAS: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRblas.0.dylib
-#> LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib
-#> 
-#> locale:
-#> [1] C/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
-#> 
-#> attached base packages:
-#> [1] stats     graphics  grDevices utils     datasets  methods   base     
-#> 
-#> other attached packages:
-#> [1] scales_0.4.1           ggplot2_2.2.1.9000     microbenchmark_1.4-2.1
-#> [4] R6_2.2.2               pryr_0.1.2            
-#> 
-#> loaded via a namespace (and not attached):
-#>  [1] Rcpp_0.12.11       knitr_1.16         magrittr_1.5      
-#>  [4] munsell_0.4.3      colorspace_1.3-2   rlang_0.1.1       
-#>  [7] stringr_1.2.0      plyr_1.8.4         tools_3.4.0       
-#> [10] grid_3.4.0         gtable_0.2.0       htmltools_0.3.6   
-#> [13] yaml_2.1.14        lazyeval_0.2.0     rprojroot_1.2     
-#> [16] digest_0.6.12      tibble_1.3.3       codetools_0.2-15  
-#> [19] evaluate_0.10      rmarkdown_1.5.9000 labeling_0.3      
-#> [22] stringi_1.1.5      compiler_3.4.0     backports_1.1.0
-
-
- - - - - - - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Portable.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Portable.R deleted file mode 100644 index cefb0cf..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Portable.R +++ /dev/null @@ -1,157 +0,0 @@ -## ----echo = FALSE-------------------------------------------------------- -knitr::opts_chunk$set(collapse = TRUE, comment = "#>") - -## ------------------------------------------------------------------------ -library(R6) -# Simulate packages by creating environments -pkgA <- new.env() -pkgB <- new.env() - -# Create a function in pkgA but not pkgB -pkgA$fun <- function() 10 - -ClassA <- R6Class("ClassA", - portable = FALSE, - public = list( - foo = function() fun() - ), - parent_env = pkgA -) - -# ClassB inherits from ClassA -ClassB <- R6Class("ClassB", - portable = FALSE, - inherit = ClassA, - parent_env = pkgB -) - -## ------------------------------------------------------------------------ -a <- ClassA$new() -a$foo() - -## ----eval=FALSE---------------------------------------------------------- -# b <- ClassB$new() -# b$foo() -# #> Error in b$foo() : could not find function "fun" - -## ------------------------------------------------------------------------ -pkgA <- new.env() -pkgB <- new.env() - -pkgA$fun <- function() { - "This function `fun` in pkgA" -} - -ClassA <- R6Class("ClassA", - portable = TRUE, # The default - public = list( - foo = function() fun() - ), - parent_env = pkgA -) - -ClassB <- R6Class("ClassB", - portable = TRUE, - inherit = ClassA, - parent_env = pkgB -) - - -a <- ClassA$new() -a$foo() - -b <- ClassB$new() -b$foo() - -## ------------------------------------------------------------------------ -pkgC <- new.env() -pkgC$fun <- function() { - "This function `fun` in pkgC" -} - -ClassC <- R6Class("ClassC", - portable = TRUE, - inherit = ClassA, - public = list( - foo = function() fun() - ), - parent_env = pkgC -) - -cc <- ClassC$new() -# This method is defined in ClassC, so finds pkgC$fun -cc$foo() - -## ------------------------------------------------------------------------ -NP <- R6Class("NP", - portable = FALSE, - public = list( - x = 1, - getxy = function() c(x, y), - sety = function(value) y <<- value - ), - private = list( - y = NA - ) -) - -np <- NP$new() - -np$sety(20) -np$getxy() - -## ----eval=FALSE---------------------------------------------------------- -# P <- R6Class("P", -# portable = TRUE, -# public = list( -# x = 1, -# getxy = function() c(x, y), -# sety = function(value) y <<- value -# ), -# private = list( -# y = NA -# ) -# ) -# -# p <- P$new() -# -# # No error, but instead of setting private$y, this sets y in the global -# # environment! This is because of the sematics of <<-. -# p$sety(20) -# y -# #> [1] 20 -# -# p$getxy() -# #> Error in p$getxy() : object 'y' not found - -## ------------------------------------------------------------------------ -P2 <- R6Class("P2", - portable = TRUE, - public = list( - x = 1, - getxy = function() c(self$x, private$y), - sety = function(value) private$y <- value - ), - private = list( - y = NA - ) -) - -p2 <- P2$new() -p2$sety(20) -p2$getxy() - -## ----eval=FALSE---------------------------------------------------------- -# ClassB <- R6Class("ClassB", -# inherit = pkgA::ClassA, -# public = list(x = 1) -# ) -# -# # We'll fill this at load time -# objB <- NULL -# -# .onLoad <- function(libname, pkgname) { -# # The namespace is locked after loading; we can still modify objB at this time. -# objB <<- ClassB$new() -# } - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Portable.Rmd b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Portable.Rmd deleted file mode 100644 index 83a760d..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Portable.Rmd +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: "Portable and non-portable R6 classes" -output: - html_document: - theme: null - css: mystyle.css - toc: yes -vignette: > - %\VignetteEngine{knitr::rmarkdown} - %\VignetteIndexEntry{Portable and non-portable R6 classes} - %\usepackage[utf8]{inputenc} ---- - -```{r echo = FALSE} -knitr::opts_chunk$set(collapse = TRUE, comment = "#>") -``` - -One limitation to R's reference classes is that class inheritance across package namespaces is limited. R6 avoids this problem when the `portable` option is enabled. - -## The problem - -Here is an example of the cross-package inheritance problem with reference classes: Suppose you have ClassA in pkgA, and ClassB in pkgB, which inherits from ClassA. ClassA has a method `foo` which calls a non-exported function `fun` in pkgA. - -If ClassB inherits `foo`, it will try to call `fun` -- but since ClassB objects are created in pkgB namespace (which is an environment) instead of the pkgA namespace, it won't be able to find `fun`. - -Something similar happens with R6 when the `portable=FALSE` option is used. For example: - -```{r} -library(R6) -# Simulate packages by creating environments -pkgA <- new.env() -pkgB <- new.env() - -# Create a function in pkgA but not pkgB -pkgA$fun <- function() 10 - -ClassA <- R6Class("ClassA", - portable = FALSE, - public = list( - foo = function() fun() - ), - parent_env = pkgA -) - -# ClassB inherits from ClassA -ClassB <- R6Class("ClassB", - portable = FALSE, - inherit = ClassA, - parent_env = pkgB -) -``` - -When we create an instance of ClassA, it works as expected: - -```{r} -a <- ClassA$new() -a$foo() -``` - -But with ClassB, it can't find the `foo` function: - -```{r eval=FALSE} -b <- ClassB$new() -b$foo() -#> Error in b$foo() : could not find function "fun" -``` - - -## Portable R6 - -R6 supports inheritance across different packages, with the default `portable=TRUE` option. In this example, we'll again simulate different packages by creating separate parent environments for the classes. - -```{r} -pkgA <- new.env() -pkgB <- new.env() - -pkgA$fun <- function() { - "This function `fun` in pkgA" -} - -ClassA <- R6Class("ClassA", - portable = TRUE, # The default - public = list( - foo = function() fun() - ), - parent_env = pkgA -) - -ClassB <- R6Class("ClassB", - portable = TRUE, - inherit = ClassA, - parent_env = pkgB -) - - -a <- ClassA$new() -a$foo() - -b <- ClassB$new() -b$foo() -``` - - -When a method is inherited from a superclass, that method also gets that class's environment. In other words, method "runs in" the superclass's environment. This makes it possible for inheritance to work across packages. - -When a method is defined in the subclass, that method gets the subclass's environment. For example, here ClassC is a subclass of ClassA, and defines its own `foo` method which overrides the `foo` method from ClassA. It happens that the method looks the same as ClassA's -- it just calls `fun`. But this time it finds `pkgC$fun` instead of `pkgA$fun`. This is in contrast to ClassB, which inherited the `foo` method and environment from ClassA. - -```{r} -pkgC <- new.env() -pkgC$fun <- function() { - "This function `fun` in pkgC" -} - -ClassC <- R6Class("ClassC", - portable = TRUE, - inherit = ClassA, - public = list( - foo = function() fun() - ), - parent_env = pkgC -) - -cc <- ClassC$new() -# This method is defined in ClassC, so finds pkgC$fun -cc$foo() -``` - - -## Using `self` - -One important difference between non-portable and portable classes is that with non-portable classes, it's possible to access members with just the name of the member, and with portable classes, member access always requires using `self$` or `private$`. This is a consequence of the inheritance implementation. - -Here's an example of a non-portable class with two methods: `sety`, which sets the private field `y` using the `<<-` operator, and `getxy`, which returns a vector with the values of fields `x` and `y`: - -```{r} -NP <- R6Class("NP", - portable = FALSE, - public = list( - x = 1, - getxy = function() c(x, y), - sety = function(value) y <<- value - ), - private = list( - y = NA - ) -) - -np <- NP$new() - -np$sety(20) -np$getxy() -``` - -If we attempt the same with a portable class, it results in an error: - -```{r eval=FALSE} -P <- R6Class("P", - portable = TRUE, - public = list( - x = 1, - getxy = function() c(x, y), - sety = function(value) y <<- value - ), - private = list( - y = NA - ) -) - -p <- P$new() - -# No error, but instead of setting private$y, this sets y in the global -# environment! This is because of the sematics of <<-. -p$sety(20) -y -#> [1] 20 - -p$getxy() -#> Error in p$getxy() : object 'y' not found -``` - -To make this work with a portable class, we need to use `self$x` and `private$y`: - -```{r} -P2 <- R6Class("P2", - portable = TRUE, - public = list( - x = 1, - getxy = function() c(self$x, private$y), - sety = function(value) private$y <- value - ), - private = list( - y = NA - ) -) - -p2 <- P2$new() -p2$sety(20) -p2$getxy() -``` - - -There is a small performance penalty for using `self$x` as opposed to `x`. In most cases, this is negligible, but it can be noticeable in some situations where there are tens of thousands or more accesses per second. For more information, see the Performance vignette. - - -## Potential pitfalls with cross-package inheritance - -Inheritance happens when an object is instantiated with `MyClass$new()`. At that time, members from the superclass get copied to the new object. This means that when you instantiate R6 object, it will essentially save some pieces of the superclass in the object. - -Because of the way that packages are built in R, R6's inheritance behavior could potentially lead to surprising, hard-to-diagnose problems when packages change versions. - -Suppose you have two packages, pkgA, containing `ClassA`, and pkgB, containing `ClassB`, and there is code in pkgB that instantiates `ClassB` in an object, `objB`, at build time. This is in contrast to instantiating `ClassB` at run-time, by calling a function. All of the code in the package is run when a *binary* package is built, and the resulting objects are saved in the package. (Generally, if the object can be accessed with `pkgB:::objB`, this means it was created at build time.) - -When `objB` is created at package build time, pieces from the superclass, `pkgA::ClassA`, are saved inside of it. This is fine in and of itself. But imagine that pkgB was built and installed against pkgA 1.0, and then you upgrade to pkgA 2.0 without subsequently building and installing pkgB. Then `pkgB::objB` will contain some code from `pkgA::ClassA` 1.0, but the version of `pkgA::ClassA` that's installed will be 2.0. This can cause problems if `objB` inherited code which uses parts of `pkgA` that have changed -- but the problems may not be entirely obvious. - -This scenario is entirely possible when installing packages from CRAN. It is very common for a package to be upgraded without upgrading all of its downstream dependencies. As far as I know, R does not have any mechanism to force downstream dependencies to be rebuilt when a package is upgraded on a user's computer. - -If this problem happens, the remedy is to rebuild pkgB against pkgA 2.0. I don't know if CRAN rebuilds all downstream dependencies when a package is updated. If it doesn't, then it's possible for CRAN to have incompatible binary builds of pkgA and pkgB, and users would then have to install pkgB from source, with `install.packages("pkgB", type = "source")`. - -To avoid this problem entirely, objects of `ClassB` must not be instantiated at build time. You can either instantiate them only in functions, or at package load time, by adding an `.onLoad` function to your package. For example: - - -```{r eval=FALSE} -ClassB <- R6Class("ClassB", - inherit = pkgA::ClassA, - public = list(x = 1) -) - -# We'll fill this at load time -objB <- NULL - -.onLoad <- function(libname, pkgname) { - # The namespace is locked after loading; we can still modify objB at this time. - objB <<- ClassB$new() -} -``` - -You might be wondering why `ClassB` (the class, not the instance of the class `objB`) doesn't save a copy of `pkgA::ClassA` inside of it when the package is built. This is because, for the `inherit` argument, `R6Class` saves the unevaluated expression, (`pkgA::ClassA`), and evaluates it when `$new()` is called. - - -## Wrap-up - -In summary: - -* Portable classes allow inheritance across different packages. -* Portable classes always require the use of `self` or `private` to access members. This can incur a small performance penalty, since using `self$x` is slower than just `x`. diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Portable.html b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Portable.html deleted file mode 100644 index 2d4096b..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/Portable.html +++ /dev/null @@ -1,252 +0,0 @@ - - - - - - - - - - - - - - -Portable and non-portable R6 classes - - - - - - - - - - - - - - - - - - - -

Portable and non-portable R6 classes

- - - - -

One limitation to R’s reference classes is that class inheritance across package namespaces is limited. R6 avoids this problem when the portable option is enabled.

-
-

The problem

-

Here is an example of the cross-package inheritance problem with reference classes: Suppose you have ClassA in pkgA, and ClassB in pkgB, which inherits from ClassA. ClassA has a method foo which calls a non-exported function fun in pkgA.

-

If ClassB inherits foo, it will try to call fun – but since ClassB objects are created in pkgB namespace (which is an environment) instead of the pkgA namespace, it won’t be able to find fun.

-

Something similar happens with R6 when the portable=FALSE option is used. For example:

-
library(R6)
-# Simulate packages by creating environments
-pkgA <- new.env()
-pkgB <- new.env()
-
-# Create a function in pkgA but not pkgB
-pkgA$fun <- function() 10
-
-ClassA <- R6Class("ClassA",
-  portable = FALSE,
-  public = list(
-    foo = function() fun()
-  ),
-  parent_env = pkgA
-)
-
-# ClassB inherits from ClassA
-ClassB <- R6Class("ClassB",
-  portable = FALSE,
-  inherit = ClassA,
-  parent_env = pkgB
-)
-

When we create an instance of ClassA, it works as expected:

-
a <- ClassA$new()
-a$foo()
-#> [1] 10
-

But with ClassB, it can’t find the foo function:

-
b <- ClassB$new()
-b$foo()
-#> Error in b$foo() : could not find function "fun"
-
-
-

Portable R6

-

R6 supports inheritance across different packages, with the default portable=TRUE option. In this example, we’ll again simulate different packages by creating separate parent environments for the classes.

-
pkgA <- new.env()
-pkgB <- new.env()
-
-pkgA$fun <- function() {
-  "This function `fun` in pkgA"
-}
-
-ClassA <- R6Class("ClassA",
-  portable = TRUE,  # The default
-  public = list(
-    foo = function() fun()
-  ),
-  parent_env = pkgA
-)
-
-ClassB <- R6Class("ClassB",
-  portable = TRUE,
-  inherit = ClassA,
-  parent_env = pkgB
-)
-
-
-a <- ClassA$new()
-a$foo()
-#> [1] "This function `fun` in pkgA"
-
-b <- ClassB$new()
-b$foo()
-#> [1] "This function `fun` in pkgA"
-

When a method is inherited from a superclass, that method also gets that class’s environment. In other words, method “runs in” the superclass’s environment. This makes it possible for inheritance to work across packages.

-

When a method is defined in the subclass, that method gets the subclass’s environment. For example, here ClassC is a subclass of ClassA, and defines its own foo method which overrides the foo method from ClassA. It happens that the method looks the same as ClassA’s – it just calls fun. But this time it finds pkgC$fun instead of pkgA$fun. This is in contrast to ClassB, which inherited the foo method and environment from ClassA.

-
pkgC <- new.env()
-pkgC$fun <- function() {
-  "This function `fun` in pkgC"
-}
-
-ClassC <- R6Class("ClassC",
-  portable = TRUE,
-  inherit = ClassA,
-  public = list(
-    foo = function() fun()
-  ),
-  parent_env = pkgC
-)
-
-cc <- ClassC$new()
-# This method is defined in ClassC, so finds pkgC$fun
-cc$foo()
-#> [1] "This function `fun` in pkgC"
-
-
-

Using self

-

One important difference between non-portable and portable classes is that with non-portable classes, it’s possible to access members with just the name of the member, and with portable classes, member access always requires using self$ or private$. This is a consequence of the inheritance implementation.

-

Here’s an example of a non-portable class with two methods: sety, which sets the private field y using the <<- operator, and getxy, which returns a vector with the values of fields x and y:

-
NP <- R6Class("NP",
-  portable = FALSE,
-  public = list(
-    x = 1,
-    getxy = function() c(x, y),
-    sety = function(value) y <<- value
-  ),
-  private = list(
-    y = NA
-  )
-)
-
-np <- NP$new()
-
-np$sety(20)
-np$getxy()
-#> [1]  1 20
-

If we attempt the same with a portable class, it results in an error:

-
P <- R6Class("P",
-  portable = TRUE,
-  public = list(
-    x = 1,
-    getxy = function() c(x, y),
-    sety = function(value) y <<- value
-  ),
-  private = list(
-    y = NA
-  )
-)
-
-p <- P$new()
-
-# No error, but instead of setting private$y, this sets y in the global
-# environment! This is because of the sematics of <<-.
-p$sety(20)
-y
-#> [1] 20
-
-p$getxy()
-#> Error in p$getxy() : object 'y' not found
-

To make this work with a portable class, we need to use self$x and private$y:

-
P2 <- R6Class("P2",
-  portable = TRUE,
-  public = list(
-    x = 1,
-    getxy = function() c(self$x, private$y),
-    sety = function(value) private$y <- value
-  ),
-  private = list(
-    y = NA
-  )
-)
-
-p2 <- P2$new()
-p2$sety(20)
-p2$getxy()
-#> [1]  1 20
-

There is a small performance penalty for using self$x as opposed to x. In most cases, this is negligible, but it can be noticeable in some situations where there are tens of thousands or more accesses per second. For more information, see the Performance vignette.

-
-
-

Potential pitfalls with cross-package inheritance

-

Inheritance happens when an object is instantiated with MyClass$new(). At that time, members from the superclass get copied to the new object. This means that when you instantiate R6 object, it will essentially save some pieces of the superclass in the object.

-

Because of the way that packages are built in R, R6’s inheritance behavior could potentially lead to surprising, hard-to-diagnose problems when packages change versions.

-

Suppose you have two packages, pkgA, containing ClassA, and pkgB, containing ClassB, and there is code in pkgB that instantiates ClassB in an object, objB, at build time. This is in contrast to instantiating ClassB at run-time, by calling a function. All of the code in the package is run when a binary package is built, and the resulting objects are saved in the package. (Generally, if the object can be accessed with pkgB:::objB, this means it was created at build time.)

-

When objB is created at package build time, pieces from the superclass, pkgA::ClassA, are saved inside of it. This is fine in and of itself. But imagine that pkgB was built and installed against pkgA 1.0, and then you upgrade to pkgA 2.0 without subsequently building and installing pkgB. Then pkgB::objB will contain some code from pkgA::ClassA 1.0, but the version of pkgA::ClassA that’s installed will be 2.0. This can cause problems if objB inherited code which uses parts of pkgA that have changed – but the problems may not be entirely obvious.

-

This scenario is entirely possible when installing packages from CRAN. It is very common for a package to be upgraded without upgrading all of its downstream dependencies. As far as I know, R does not have any mechanism to force downstream dependencies to be rebuilt when a package is upgraded on a user’s computer.

-

If this problem happens, the remedy is to rebuild pkgB against pkgA 2.0. I don’t know if CRAN rebuilds all downstream dependencies when a package is updated. If it doesn’t, then it’s possible for CRAN to have incompatible binary builds of pkgA and pkgB, and users would then have to install pkgB from source, with install.packages("pkgB", type = "source").

-

To avoid this problem entirely, objects of ClassB must not be instantiated at build time. You can either instantiate them only in functions, or at package load time, by adding an .onLoad function to your package. For example:

-
ClassB <- R6Class("ClassB",
-  inherit = pkgA::ClassA,
-  public = list(x = 1)
-)
-
-# We'll fill this at load time
-objB <- NULL
-
-.onLoad <- function(libname, pkgname) {
-  # The namespace is locked after loading; we can still modify objB at this time.
-  objB <<- ClassB$new()
-}
-

You might be wondering why ClassB (the class, not the instance of the class objB) doesn’t save a copy of pkgA::ClassA inside of it when the package is built. This is because, for the inherit argument, R6Class saves the unevaluated expression, (pkgA::ClassA), and evaluates it when $new() is called.

-
-
-

Wrap-up

-

In summary:

-
    -
  • Portable classes allow inheritance across different packages.
  • -
  • Portable classes always require the use of self or private to access members. This can incur a small performance penalty, since using self$x is slower than just x.
  • -
-
- - - - - - - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/index.html b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/index.html deleted file mode 100644 index 348d4d5..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/doc/index.html +++ /dev/null @@ -1,43 +0,0 @@ - - -R: Vignettes and other documentation - - - -

Vignettes and other documentation - -

-
-
-[Top] -
-

Vignettes from package 'R6'

- ------- - - - - - - - - - - - - - - - - - - - -
R6::DebuggingDebugging methods in R6 objectsHTMLsourceR code
R6::IntroductionIntroduction to R6 classesHTMLsourceR code
R6::PerformanceR6 and Reference class performance testsHTMLsourceR code
R6::PortablePortable and non-portable R6 classesHTMLsourceR code
- diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/AnIndex b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/AnIndex deleted file mode 100644 index 05d6e1a..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/AnIndex +++ /dev/null @@ -1,5 +0,0 @@ -as.list.R6 as.list.R6 -is.R6 is.R6 -is.R6Class is.R6 -R6 R6Class -R6Class R6Class diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/R6.rdb b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/R6.rdb deleted file mode 100644 index de1c245..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/R6.rdb and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/R6.rdx b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/R6.rdx deleted file mode 100644 index 31b37e7..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/R6.rdx and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/aliases.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/aliases.rds deleted file mode 100644 index 7cc9efd..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/aliases.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/paths.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/paths.rds deleted file mode 100644 index 360f420..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/help/paths.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/html/00Index.html b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/html/00Index.html deleted file mode 100644 index aa293f5..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/html/00Index.html +++ /dev/null @@ -1,35 +0,0 @@ - - -R: Classes with Reference Semantics - - - -

Classes with Reference Semantics - -

-
-
-[Up] -[Top] -

Documentation for package ‘R6’ version 2.2.2

- - - -

Help Pages

- - - - - - - - - - - - - -
as.list.R6Create a list from an R6 object
is.R6Is an object an R6 Class Generator or Object?
is.R6ClassIs an object an R6 Class Generator or Object?
R6Create an R6 reference object generator
R6ClassCreate an R6 reference object generator
- diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/html/R.css b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/html/R.css deleted file mode 100644 index f10f5ea..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/R6/html/R.css +++ /dev/null @@ -1,97 +0,0 @@ -body { - background: white; - color: black; -} - -a:link { - background: white; - color: blue; -} - -a:visited { - background: white; - color: rgb(50%, 0%, 50%); -} - -h1 { - background: white; - color: rgb(55%, 55%, 55%); - font-family: monospace; - font-size: x-large; - text-align: center; -} - -h2 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-size: large; - text-align: center; -} - -h3 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-size: large; -} - -h4 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-style: italic; - font-size: large; -} - -h5 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; -} - -h6 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-style: italic; -} - -img.toplogo { - width: 4em; - vertical-align: middle; -} - -img.arrow { - width: 30px; - height: 30px; - border: 0; -} - -span.acronym { - font-size: small; -} - -span.env { - font-family: monospace; -} - -span.file { - font-family: monospace; -} - -span.option{ - font-family: monospace; -} - -span.pkg { - font-weight: bold; -} - -span.samp{ - font-family: monospace; -} - -div.vignettes a:hover { - background: rgb(85%, 85%, 85%); -} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/CITATION b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/CITATION deleted file mode 100644 index 49f85fc..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/CITATION +++ /dev/null @@ -1,32 +0,0 @@ -citHeader("To cite Rcpp in publications use:") - -citEntry(entry = "Article", - title = "{Rcpp}: Seamless {R} and {C++} Integration", - author = personList(as.person("Dirk Eddelbuettel"), - as.person("Romain Fran\\c{c}ois")), - journal = "Journal of Statistical Software", - year = "2011", - volume = "40", - number = "8", - pages = "1--18", - url = "http://www.jstatsoft.org/v40/i08/", - - textVersion = - paste("Dirk Eddelbuettel and Romain Francois (2011).", - "Rcpp: Seamless R and C++ Integration.", - "Journal of Statistical Software, 40(8), 1-18.", - "URL http://www.jstatsoft.org/v40/i08/.") -) - -citEntry(entry = "Book", - title = "Seamless {R} and {C++} Integration with {Rcpp}", - author = personList(as.person("Dirk Eddelbuettel")), - publisher = "Springer", - address = "New York", - year = 2013, - note = "ISBN 978-1-4614-6867-7", - - textVersion = paste("Eddelbuettel, Dirk (2013)", - "Seamless R and C++ Integration with Rcpp.", - "Springer, New York. ISBN 978-1-4614-6867-7.") -) diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/DESCRIPTION b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/DESCRIPTION deleted file mode 100644 index 84835d3..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/DESCRIPTION +++ /dev/null @@ -1,36 +0,0 @@ -Package: Rcpp -Title: Seamless R and C++ Integration -Version: 0.12.12 -Date: 2017-07-13 -Author: Dirk Eddelbuettel, Romain Francois, JJ Allaire, Kevin Ushey, - Qiang Kou, Nathan Russell, Douglas Bates and John Chambers -Maintainer: Dirk Eddelbuettel -Description: The 'Rcpp' package provides R functions as well as C++ - classes which offer a seamless integration of R and C++. Many R - data types and objects can be mapped back and forth to C++ - equivalents which facilitates both writing of new code as well as - easier integration of third-party libraries. Documentation about - 'Rcpp' is provided by several vignettes included in this package, - via the 'Rcpp Gallery' site at , the paper - by Eddelbuettel and Francois (2011, JSS), and the book by - Eddelbuettel (2013, Springer); see 'citation("Rcpp")' for details - on these last two. -Depends: R (>= 3.0.0) -Imports: methods, utils -Suggests: RUnit, inline, rbenchmark, highlight, pkgKitten (>= 0.1.2) -VignetteBuilder: highlight -URL: http://www.rcpp.org, http://dirk.eddelbuettel.com/code/rcpp.html, - https://github.com/RcppCore/Rcpp -License: GPL (>= 2) -BugReports: https://github.com/RcppCore/Rcpp/issues -MailingList: Please send questions and comments regarding Rcpp to - rcpp-devel@lists.r-forge.r-project.org -RoxygenNote: 5.0.1 -NeedsCompilation: yes -Packaged: 2017-07-13 11:40:06.188015 UTC; edd -Repository: CRAN -Date/Publication: 2017-07-15 12:02:11 UTC -Built: R 3.4.1; x86_64-pc-linux-gnu; 2017-09-09 18:08:21 UTC; unix -InstallAgent: packrat 0.4.8.38 -InstallSource: CRAN -Hash: 8b3d5ebb9a9a4ab5c86b3a81b0cfb774 diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/INDEX b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/INDEX deleted file mode 100644 index bfbd0a1..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/INDEX +++ /dev/null @@ -1,37 +0,0 @@ -.DollarNames-methods completion -C++Class-class Reflection information for an internal c++ - class -C++Constructor-class Class "C++Constructor" -C++Field-class Class "C++Field" -C++Function-class Class "C++Function" -C++Object-class c++ internal objects -C++OverloadedMethods-class - Class "C++OverloadedMethods" -LdFlags (Deprecated) Rcpp Linker Flags -Module Retrieves an Rcpp module -Module-class Rcpp modules -Rcpp-deprecated Deprecated Functions in the Rcpp Package -Rcpp-package R / C++ interface -Rcpp.package.skeleton Create a skeleton for a new package depending - on Rcpp -Rcpp.plugin.maker Facilitating making package plugins -RcppUnitTests Rcpp : unit tests results -compileAttributes Compile Rcpp Attributes for a Package -compilerCheck Check for Minimal (g++) Compiler Version -cppFunction Define an R Function with a C++ Implementation -demangle c++ type information -dependsAttribute Rcpp::depends Attribute -evalCpp Evaluate a C++ Expression -exportAttribute Rcpp::export Attribute -exposeClass Create an Rcpp Module to Expose a C++ Class in - R -formals<--methods Set the formal arguments of a C++ function -interfacesAttribute Rcpp::interfaces Attribute -loadModule Load an Rcpp Module into a Package -loadRcppModules Loads Rcpp modules on package startup -pluginsAttribute Rcpp::plugins Attribute -populate Populates a namespace or an environment with - the content of a module -registerPlugin Register an inline plugin -setRcppClass Create a Class Extending a C++ Class -sourceCpp Source C++ Code from a File or String diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/Rd.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/Rd.rds deleted file mode 100644 index dc9cb75..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/Rd.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/features.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/features.rds deleted file mode 100644 index 2027d3f..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/features.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/hsearch.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/hsearch.rds deleted file mode 100644 index c4e84f3..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/hsearch.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/links.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/links.rds deleted file mode 100644 index 6ab90c5..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/links.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/nsInfo.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/nsInfo.rds deleted file mode 100644 index dbaf171..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/nsInfo.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/package.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/package.rds deleted file mode 100644 index b5838eb..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/package.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/vignette.rds b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/vignette.rds deleted file mode 100644 index 518ece0..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/Meta/vignette.rds and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/NAMESPACE b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/NAMESPACE deleted file mode 100644 index 2c7e210..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/NAMESPACE +++ /dev/null @@ -1,43 +0,0 @@ -useDynLib(Rcpp, .registration = TRUE) - -import(methods) -importFrom(utils, capture.output, assignInNamespace, .DollarNames, prompt, - packageDescription, package.skeleton, glob2rx) - -exportClasses(Module, "C++Field", - "C++OverloadedMethods", - "C++Constructor", - "C++Class", "C++Object", "C++Function") - -S3method(.DollarNames, "C++Object") -S3method(.DollarNames, "Module") -exportMethods(prompt, show, .DollarNames, initialize, "formals<-") - -export(Module, - Rcpp.package.skeleton, - populate, - loadRcppModules, # deprecated since Rcpp 0.12.5 - setRcppClass, - loadRcppClass, - loadModule, - cppFunction, - exposeClass, - evalCpp, - sourceCpp, - compileAttributes, - registerPlugin, - RcppLdFlags, - LdFlags, - demangle, - sizeof, - cpp_object_initializer, - cpp_object_dummy, - Rcpp.plugin.maker - ) -S3method(print, bytes) -S3method(format, Rcpp_stack_trace) -S3method(str, Rcpp_stack_trace) -S3method(print, Rcpp_stack_trace) -exportClass(RcppClass) - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/NEWS.Rd b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/NEWS.Rd deleted file mode 100644 index e1f0d26..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/NEWS.Rd +++ /dev/null @@ -1,2241 +0,0 @@ -\name{NEWS} -\title{News for Package \pkg{Rcpp}} -\newcommand{\ghpr}{\href{https://github.com/RcppCore/Rcpp/pull/#1}{##1}} -\newcommand{\ghit}{\href{https://github.com/RcppCore/Rcpp/issues/#1}{##1}} - -\section{Changes in Rcpp version 0.12.12 (2017-07-13)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item The \code{tinyformat.h} header now ends in a newline (\ghit{701}). - \item Fixed rare protection error that occurred when fetching stack traces - during the construction of an Rcpp exception (Kirill Müller in \ghpr{706}). - \item Compilation is now also possibly on Haiku-OS (Yo Gong in \ghpr{708} - addressing \ghit{707}). - \item Dimension attributes are explicitly cast to \code{int} (Kirill - Müller in \ghpr{715}). - \item Unused arguments are no longer declared (Kirill Müller in - \ghpr{716}). - \item Visibility of exported functions is now supported via the R macro - \code{atttribute_visible} (Jeroen Ooms in \ghpr{720}). - \item The \code{no_init()} constructor accepts \code{R_xlen_t} (Kirill - Müller in \ghpr{730}). - \item Loop unrolling used \code{R_xlen_t} (Kirill Müller in \ghpr{731}). - \item Two unused-variables warnings are now avoided (Jeff Pollock in - \ghpr{732}). - } - \item Changes in Rcpp Attributes: - \itemize{ - \item Execute tools::package_native_routine_registration_skeleton - within package rather than current working directory (JJ in \ghpr{697}). - \item The R portion no longer uses \code{dir.exists} to no require R 3.2.0 - or newer (Elias Pipping in \ghpr{698}). - \item Fix native registration for exports with name attribute (JJ in \ghpr{703} - addressing \ghit{702}). - \item Automatically register init functions for Rcpp Modules (JJ in \ghpr{705} - addressing \ghit{704}). - \item Add Shield around parameters in Rcpp::interfaces (JJ in \ghpr{713} - addressing \ghit{712}). - \item Replace dot (".") with underscore ("_") in package names when generating - native routine registrations (JJ in \ghpr{722} addressing \ghit{721}). - \item Generate C++ native routines with underscore ("_") prefix to avoid - exporting when standard exportPattern is used in NAMESPACE (JJ in - \ghpr{725} addressing \ghit{723}). - } - } -} - -\section{Changes in Rcpp version 0.12.11 (2017-05-20)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item Rcpp::exceptions can now be constructed without a call stack (Jim - Hester in \ghpr{663} addressing \ghit{664}). - \item Somewhat spurious compiler messages under very verbose settings are - now suppressed (Kirill Mueller in \ghpr{670}, \ghpr{671}, \ghpr{672}, - \ghpr{687}, \ghpr{688}, \ghpr{691}). - \item Refreshed the included \code{tinyformat} template library - (James Balamuta in \ghpr{674} addressing \ghit{673}). - \item Added \code{printf}-like syntax support for exception classes and - variadic templating for \code{Rcpp::stop} and \code{Rcpp::warning} - (James Balamuta in \ghpr{676}). - \item Exception messages have been rewritten to provide additional - information. (James Balamuta in \ghpr{676} and \ghpr{677} addressing - \ghit{184}). - \item One more instance of \code{Rf_mkString} is protected from garbage - collection (Dirk in \ghpr{686} addressing \ghit{685}). - \item Two exception specification that are no longer tolerated by - \code{g++-7.1} or later were removed (Dirk in \ghpr{690} addressing - \ghit{689}) - } - \item Changes in Rcpp Documentation: - \itemize{ - \item Added a Known Issues section to the Rcpp FAQ vignette - (James Balamuta in \ghpr{661} addressing \ghit{628}, \ghit{563}, - \ghit{552}, \ghit{460}, \ghit{419}, and \ghit{251}). - } - \item Changes in Rcpp Sugar: - \itemize{ - \item Added sugar function \code{trimws} (Nathan Russell in \ghpr{680} - addressing \ghit{679}). - } - \item Changes in Rcpp Attributes: - \itemize{ - \item Automatically generate native routine registrations (JJ in \ghpr{694}) - \item The plugins for C++11, C++14, C++17 now set the values R 3.4.0 or - later expects; a plugin for C++98 was added (Dirk in \ghpr{684} addressing - \ghit{683}). - } - \item Changes in Rcpp support functions: - \itemize{ - \item The \code{Rcpp.package.skeleton()} function now creates a package - registration file provided R 3.4.0 or later is used (Dirk in \ghpr{692}) - } - } -} - -\section{Changes in Rcpp version 0.12.10 (2017-03-17)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item Added new size attribute aliases for number of rows and columns in - DataFrame (James Balamuta in \ghpr{638} addressing \ghit{630}). - \item Fixed single-character handling in \code{Rstreambuf} (Iñaki Ucar in - \ghpr{649} addressing \ghit{647}). - \item XPtr gains a parameter \code{finalizeOnExit} to enable running the - finalizer when R quits (Jeroen Ooms in \ghpr{656} addressing \ghit{655}). - } - \item Changes in Rcpp Sugar: - \itemize{ - \item Fixed sugar functions \code{upper_tri()} and \code{lower_tri()} - (Nathan Russell in \ghpr{642} addressing \ghit{641}). - \item The \code{algorithm.h} file now accomodates the Intel compiler - (Dirk in \ghpr{643} and Dan in \ghpr{645} addressing issue \ghit{640}). - } - \item Changes in Rcpp Attributes: - \itemize{ - \item The C++17 standard is supported with a new plugin (used eg for - \code{g++-6.2}). - } - \item Changes in Rcpp Documentation: - \itemize{ - \item An overdue explanation of how C++11, C++14, and C++17 can be used - was added to the Rcpp FAQ. - } - } -} - -\section{Changes in Rcpp version 0.12.9 (2017-01-14)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item The exception stack message is now correctly demangled on all - compiler versions (Jim Hester in \ghpr{598}) - \item Date and Datetime object and vector now have format methods and - \code{operator<<} support (\ghpr{599}). - \item The \code{size} operator in \code{Matrix} is explicitly referenced - avoiding a g++-6 issues (\ghpr{607} fixing \ghit{605}). - \item The underlying date calculation code was updated (\ghpr{621}, - \ghpr{623}). - \item Addressed improper diagonal fill for non-symmetric matrices - (James Balamuta in \ghpr{622} addressing \ghit{619}) - } - \item Changes in Rcpp Sugar: - \itemize{ - \item Added new Sugar function \code{sample()} (Nathan Russell in - \ghpr{610} and \ghpr{616}). - \item Added new Sugar function \code{Arg()} (James Balamuta in - \ghpr{626} addressing \ghit{625}). - } - \item Changes in Rcpp unit tests - \itemize{ - \item Added Environment::find unit tests and an Environment::get(Symbol) - test (James Balamuta in \ghpr{595} addressing issue \ghit{594}). - \item Added diagonal matrix fill tests - (James Balamuta in \ghpr{622} addressing \ghit{619}) - } - \item Changes in Rcpp Documentation: - \itemize{ - \item Exposed pointers macros were included in the Rcpp Extending vignette - (MathurinD; James Balamuta in \ghpr{592} addressing \ghit{418}). - \item The file \code{Rcpp.bib} move to directory \code{bib} which is - guaranteed to be present (\ghpr{631}). - } - \item Changes in Rcpp build system - \itemize{ - \item Travis CI now also calls \CRANpkg{covr} for coverage analysis (Jim - Hester in PR \ghpr{591}) - } - } -} - -\section{Changes in Rcpp version 0.12.8 (2016-11-16)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item String and vector elements now use extended \code{R_xlen_t} indices - (Qiang in PR \ghpr{560}) - \item Hashing functions now return unsigned int (Qiang in PR \ghpr{561}) - \item Added static methods \code{eye()}, \code{ones()}, and \code{zeros()} - for select matrix types (Nathan Russell in PR \ghpr{569}) - \item The exception call stack is again correctly reported; print methods - and tests added too (Jim Hester in PR \ghpr{582} fixing \ghit{579}) - \item Variatic macros no longer use a GNU extensions (Nathan in PR - \ghpr{575}) - \item Hash index functions were standardized on returning unsigned - integers (Also PR \ghpr{575}) - } - \item Changes in Rcpp Sugar: - \itemize{ - \item Added new Sugar functions \code{rowSums()}, \code{colSums()}, - \code{rowMeans()}, \code{colMeans()} (PR \ghpr{551} by Nathan Russell - fixing \ghit{549}) - \item \code{Range} Sugar now used \code{R_xlen_t} type for start/end - (PR \ghpr{568} by Qiang Kou) - \item Defining \code{RCPP_NO_SUGAR} no longer breaks the build. - (PR \ghpr{585} by Daniel C. Dillon) - } - \item Changes in Rcpp unit tests - \itemize{ - \item A test for expression vectors was corrected. - \item The constructor test for datetime vectors reflects the new classes - which treats Inf correctly (and still as a non-finite value) - } - \item Changes in Rcpp Attributes - \itemize{ - \item An 'empty' return was corrected (PR \ghpr{589} fixing issue - \ghit{588}, and with thanks to Duncan Murdoch for the heads-up) - } - \item Updated Date and Datetime vector classes: - \itemize{ - \item The \code{DateVector} and \code{DatetimeVector} classes were renamed - with a prefix \code{old}; they are currently \code{typedef}'ed to the - existing name (\ghpr{557}) - \item New variants \code{newDateVector} and \code{newDatetimeVector} were - added based on \code{NumericVector} (also \ghpr{557}, \ghpr{577}, - \ghpr{581}, \ghpr{587}) - \item By defining \code{RCPP_NEW_DATE_DATETIME_VECTORS} the new classes - can activated. We intend to make the new classes the default no sooner - than twelve months from this release. - \item The \code{capabilities()} function can also be used for presence of - this feature - } - } -} - -\section{Changes in Rcpp version 0.12.7 (2016-09-04)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item The \code{NORET} macro is now defined if it was not already defined - by R itself (Kevin fixing issue \ghit{512}). - \item Environment functions get() & find() now accept a Symbol - (James Balamuta in \ghpr{513} addressing issue \ghit{326}). - \item Several uses of \code{Rf_eval} were replaced by the preferred - \code{Rcpp::Rcpp_eval} (Qiang in PR \ghpr{523} closing \ghit{498}). - \item Improved Autogeneration Warning for RcppExports - (James Balamuta in \ghpr{528} addressing issue \ghit{526}). - \item Fixed invalid C++ prefix identifiers in auto-generated code - (James Balamuta in \ghpr{528} and \ghpr{531} addressing issue - \ghit{387}; Simon Dirmeier in \ghpr{548}). - \item String constructors now set default UTF-8 encoding (Qiang Kou in - \ghpr{529} fixing \ghit{263}). - \item Add variadic variants of the \code{RCPP_RETURN_VECTOR} and - \code{RCPP_RETURN_MATRIX} macro when C++11 compiler used (Artem Klevtsov - in \ghpr{537} fixing \ghit{38}). - } - \item Changes in Rcpp build system - \itemize{ - \item Travis CI is now driven via \code{run.sh} from our fork, and deploys - all packages as .deb binaries using our PPA where needed (Dirk in - \ghpr{540} addressing issue \ghit{517}). - } - \item Changes in Rcpp unit tests - \itemize{ - \item New unit tests for random number generators the R namespace which - call the standalone Rmath library. (James Balamuta in \ghpr{514} - addressing issue \ghit{28}). - } - \item Changes in Rcpp Examples: - \itemize{ - \item Examples that used cxxfunction() from the inline package have been - rewritten to use either sourceCpp() or cppFunction() - (James Balamuta in \ghpr{541}, \ghpr{535}, \ghpr{534}, and \ghpr{532} - addressing issue \ghit{56}). - } - } -} - -\section{Changes in Rcpp version 0.12.6 (2016-07-18)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item The \code{long long} data type is used only if it is available, - to avoid compiler warnings (Kirill Müller in \ghpr{488}). - \item The compiler is made aware that \code{stop()} never returns, to - improve code path analysis (Kirill Müller in \ghpr{487} addressing issue - \ghit{486}). - \item String replacement was corrected (Qiang in \ghpr{479} following - mailing list bug report by Masaki Tsuda) - \item Allow for UTF-8 encoding in error messages via - \code{RCPP_USING_UTF8_ERROR_STRING} macro (Qin Wenfeng in \ghpr{493}) - \item The R function \code{Rf_warningcall} is now provided as well (as - usual without leading \code{Rf_}) (\ghpr{497} fixing \ghit{495}) - } - \item Changes in Rcpp Sugar: - \itemize{ - \item Const-ness of \code{min} and \code{max} functions has been corrected. - (Dan Dillon in PR \ghpr{478} fixing issue \ghit{477}). - \item Ambiguities for matrix/vector and scalar operations have been fixed - (Dan Dillon in PR \ghpr{476} fixing issue \ghit{475}). - \item New \code{algorithm} header using iterator-based approach for - vectorized functions (Dan in PR \ghpr{481} revisiting PR \ghpr{428} and - addressing issue \ghit{426}, with futher work by Kirill in PR \ghpr{488} - and Nathan in \ghpr{503} fixing issue \ghit{502}). - \item The \code{na_omit()} function is now faster for vectors without - \code{NA} values (Artem Klevtsov in PR \ghpr{492}) - } - \item Changes in Rcpp Attributes: - \itemize{ - \item Add \code{cacheDir} argument to \code{sourceCpp()} to enable caching of - shared libraries across R sessions (JJ in \ghpr{504}). - \item Code generation now deals correctly which packages containing a dot - in their name (Qiang in \ghpr{501} fixing \ghit{500}). - } - \item Changes in Rcpp Documentation: - \itemize{ - \item A section on default parameters was added to the Rcpp FAQ vignette - (James Balamuta in \ghpr{505} fixing \ghit{418}). - \item The Rcpp-attributes vignette is now mentioned more prominently in - question one of the Rcpp FAQ vignette. - \item The Rcpp Quick Reference vignette received a facelift with new - sections on Rcpp attributes and plugins begin added. (James Balamuta in - \ghpr{509} fixing \ghit{484}). - \item The bib file was updated with respect to the recent JSS publication - for RProtoBuf. - } - } -} - -\section{Changes in Rcpp version 0.12.5 (2016-05-14)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item The checks for different C library implementations now also check for Musl - used by Alpine Linux (Sergio Marques in PR \ghpr{449}). - \item \code{Rcpp::Nullable} works better with Rcpp::String (Dan Dillon in - PR \ghpr{453}). - } - \item Changes in Rcpp Attributes: - \itemize{ - \item R 3.3.0 Windows with Rtools 3.3 is now supported (Qin Wenfeng in PR - \ghpr{451}). - \item Correct handling of dependent file paths on Windows (use winslash = "/"). - } - \item Changes in Rcpp Modules: - \itemize{ - \item An apparent race condition in Module loading seen with R 3.3.0 was - fixed (Ben Goodrich in \ghpr{461} fixing \ghit{458}). - \item The (older) \code{loadRcppModules()} is now deprecated in favour of - \code{loadModule()} introduced around R 2.15.1 and Rcpp 0.9.11 (PR \ghpr{470}). - } - \item Changes in Rcpp support functions: - \itemize{ - \item The \code{Rcpp.package.skeleton()} function was again updated in - order to create a \code{DESCRIPTION} file which passes \code{R CMD check} - without notes. warnings, or error under R-release and R-devel (PR \ghpr{471}). - \item A new function \code{compilerCheck} can test for minimal \code{g++} - versions (PR \ghpr{474}). - } - } -} - -\section{Changes in Rcpp version 0.12.4 (2016-03-22)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item New accessors \code{as()} and \code{clone()} were added to the - \code{Nullable} class (Dan in PR \ghpr{423} closing \ghit{421}) - \item The \code{Nullable<>::operator SEXP()} and - \code{Nullable<>::get()} now also work for \code{const} objects - (Kirill Mueller in PR \ghpr{417}). - \item A subsetting error was fixed (Qiang via \ghpr{432} closing - \ghit{431}). - } - \item Changes in Rcpp Sugar: - \itemize{ - \item Added new Sugar function \code{median()} (Nathan in PR \ghpr{425} - closing \ghit{424}) - \item Added new Sugar function \code{cbind()} (Nathan in PR \ghpr{447} - closing \ghit{407}) - } - \item Changes in Rcpp Attributes: - \itemize{ - \item A plugin for C++14 was added (Dan in PR \ghpr{427}) - } - \item Changes in Rcpp Documentation: - \itemize{ - \item An entry was added to the Rcpp-FAQ vignette describing the required - packages for vignette building (\ghit{422}). - \item Use on OS X was further detailed (James Balamuta in \ghpr{433} with - further review by Bob Rudis). - \item An entry was added concerning the hard-code limit of arguments to - some constructor and function (cf \ghit{435}). - \item The Rcpp-FAQ vignette now contains a table of content. - \item Typos and indentation were corrected in the Rcpp Sugar vignette - (\ghpr{445} by Colin Gillespie). - } - } -} - -\section{Changes in Rcpp version 0.12.3 (2016-01-10)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item Const iterators now \code{CharacterVector} now behave like regular - iterators (PR \ghpr{404} by Dan fixing \ghit{362}). - \item Math operators between matrix and scalars type have been added (PR - \ghpr{406} by Qiang fixing \ghit{365}). - \item A missing \code{std::hash} function interface for - \code{Rcpp::String} has been addded (PR \ghpr{408} by Qiang fixing - \ghit{84}). - } - \item Changes in Rcpp Attributes: - \itemize{ - \item Avoid invalid function names when generating C++ interfaces (PR - \ghpr{403} by JJ fixing \ghit{402}). - \item Insert additional space around \code{&} in function interface (PR - \ghpr{400} by Kazuki Fukui fixing \ghit{278}). - } - \item Changes in Rcpp Modules: - \itemize{ - \item The copy constructor now initialized the base class (PR \ghpr{411} - by Joshua Pritikin fixing \ghit{410}) - } - \item Changes in Rcpp Repository: - \itemize{ - \item Added a file \code{Contributing.md} providing some points to - potential contributors (PR \ghpr{414} closing issue \ghit{413}) - } - } -} - -\section{Changes in Rcpp version 0.12.2 (2015-11-14)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item Correct return type in product of matrix dimensions (PR \ghpr{374} - by Florian) - \item Before creating a single String object from a \code{SEXP}, ensure - that it is from a vector of length one (PR \ghpr{376} by Dirk, fixing - \ghit{375}). - \item No longer use \code{STRING_ELT} as a left-hand side, thanks to a - heads-up by Luke Tierney (PR \ghpr{378} by Dirk, fixing \ghit{377}). - \item Rcpp Module objects are now checked more carefully (PR \ghpr{381} - by Tianqi, fixing \ghit{380}) - \item An overflow in Matrix column indexing was corrected (PR \ghpr{390} - by Qiang, fixing a bug reported by Allessandro on the list) - \item \code{Nullable} types can now be assigned \code{R_NilValue} in - function signatures. (PR \ghpr{395} by Dan, fixing issue \ghit{394}) - \item \code{operator<<()} now always shows decimal points (PR \ghpr{396} - by Dan) - \item Matrix classes now have a \code{transpose()} function (PR \ghpr{397} - by Dirk fixing \ghit{383}) - \item \code{operator<<()} for complex types was added (PRs \ghpr{398} by - Qiang and \ghpr{399} by Dirk, fixing \ghit{187}) - } - \item Changes in Rcpp Attributes: - \itemize{ - \item Enable export of C++ interface for functions that return void. - } - \item Changes in Rcpp Sugar: - \itemize{ - \item Added new Sugar function \code{cummin()}, \code{cummax()}, - \code{cumprod()} (PR \ghpr{389} by Nathan Russell fixing \ghit{388}) - \item Enabled sugar math operations for subsets; e.g. x[y] + x[z]. - (PR \ghpr{393} by Kevin and Qiang, implementing \ghit{392}) - } - \item Changes in Rcpp Documentation: - \itemize{ - \item The \code{NEWS} file now links to GitHub issue tickets and pull - requests. - \item The \code{Rcpp.bib} file with bibliographic references was updated. - } - } -} - -\section{Changes in Rcpp version 0.12.1 (2015-09-10)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item Correct use of WIN32 instead of _WIN32 to please Windows 10 - \item Add an assignment operator to \code{DimNameProxy} (PR \ghpr{339} by Florian) - \item Add vector and matrix accessors \code{.at()} with bounds checking - (PR \ghpr{342} by Florian) - \item Correct character vector conversion from single char (PR \ghpr{344} by - Florian fixing issue \ghit{343}) - \item Correct on use of \code{R_xlen_t} back to \code{size_t} (PR \ghpr{348} by - Romain) - \item Correct subsetting code to allow for single assignment (PR \ghpr{349} by - Florian) - \item Enable subset assignment on left and righ-hand side (PR \ghpr{353} by - Qiang, fixing issue \ghit{345}) - \item Refreshed to included \code{tinyformat} template library (PR \ghpr{357} by - Dirk, issue \ghit{356}) - \item Add \code{operator<<()} for vectors and matrices (PR \ghpr{361} by Dan - fixing issue \ghit{239}) - \item Make \code{String} and \code{String_Proxy} objects comparable (PR - \ghpr{366} and PR \ghpr{372} by Dan, fixing issue \ghit{191}) - \item Add a new class \code{Nullable} for objects which may be \code{NULL} - (PR \ghpr{368} by Dirk and Dan, fixing issue \ghit{363}) - \item Correct creation and access of large matrices (PR \ghpr{370} by Florian, - fixing issue \ghit{369}) - } - \item Changes in Rcpp Attributes: - \itemize{ - \item Correctly reset directory in case of no-rebuilding but Windows code - (PR \ghpr{335} by Dirk) - } - \item Changes in Rcpp Modules: - \itemize{ - \item We no longer define multiple Modules objects named \code{World} in - the unit tests with was seen to have a bad effect with R 3.2.2 or later - (PR \ghpr{351} by Dirk fixing issue \ghit{350}). - \item Applied patch by Kurt Hornik which improves how Rcpp loads Modules - (PR \ghpr{353} by Dirk) - } - \item Changes in Rcpp Documentation: - \itemize{ - \item The \code{Rcpp.bib} file with bibliographic references was updated. - } - } -} - -\section{Changes in Rcpp version 0.12.0 (2015-07-24)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item \code{Rcpp_eval()} no longer uses \code{R_ToplevelExec} when evaluating - R expressions; this should resolve errors where calling handlers (e.g. - through \code{suppressMessages()}) were not properly respected. - \item All internal length variables have been changed from \code{R_len_t} - to \code{R_xlen_t} to support vectors longer than 2^31-1 elements (via - PR \ghpr{303} by Qiang Kou). - \item The sugar function \code{sapply} now supports lambda functions - (addressing \ghit{213} thanks to Matt Dziubinski) - \item The \code{var} sugar function now uses a more robust two-pass - method, supports complex numbers, with new unit tests added (via PR - \ghpr{320} by Matt Dziubinski) - \item \code{String} constructors now allow encodings (via PR \ghpr{310} - by Qiang Kou) - \item \code{String} objects are preserving the underlying \code{SEXP} - objects better, and are more careful about initializations (via PRs - \ghpr{322} and \ghpr{329} by Qiang Kou) - \item DataFrame constructors are now a little more careful (via PR - \ghpr{301} by Romain Francois) - \item For R 3.2.0 or newer, \code{Rf_installChar()} is used instead of - \code{Rf_install(CHAR())} (via PR \ghpr{332}). - } - \item Changes in Rcpp Attributes: - \itemize{ - \item Use more robust method of ensuring unique paths for generated shared - libraries. - \item The \code{evalCpp} function now also supports the \code{plugins} - argument. - \item Correctly handle signature termination characters ('\{' or ';') contained - in quotes. - } - \item Changes in Rcpp Documentation: - \itemize{ - \item The \code{Rcpp-FAQ} vignette was once again updated with respect to - OS X issues and Fortran libraries needed for e.g. \CRANpkg{RcppArmadillo}. - \item The included \code{Rcpp.bib} bibtex file (which is also used by - other Rcpp* packages) was updated with respect to its CRAN references. - } - } -} - -\section{Changes in Rcpp version 0.11.6 (2015-05-01)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item The unwinding of exceptions was refined to protect against inadvertent - memory leaks. - \item Header files now try even harder not to let macro definitions leak. - \item Matrices have a new default constructor for zero-by-zero dimension - matrices (via a pull request by Dmitrii Meleshko). - \item A new \code{empty()} string constructor was added (via another pull - request). - \item Better support for Vectors with a storage policy different from the - default, i.e. \code{NoProtectStorage}, was added. - } - \item Changes in Rcpp Attributes: - \itemize{ - \item Rtools 3.3 is now supported. - } - } -} - -\section{Changes in Rcpp version 0.11.5 (2015-03-04)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item An error handler for tinyformat was defined to prevent the \code{assert()} - macro from spilling. - \item The \code{Rcpp::warning} function was added as a wrapper for \code{Rf_warning}. - \item The \code{XPtr} class was extended with new \code{checked_get} - and \code{release} functions as well as improved behavior (throw an - exception rather than crash) when a NULL external pointer is dereferenced. - \item R code is evaluated within an \code{R_toplevelExec} block to prevent - user interrupts from bypassing C++ destructors on the stack. - \item The \code{Rcpp::Environment} constructor can now use a supplied - parent environment. - \item The \code{Rcpp::Function} constructor can now use a supplied - environment or namespace. - \item The \code{attributes_hidden} macro from R is used to shield internal - functions; the \code{R_ext/Visibility.h} header is now included as well. - \item A \code{Rcpp::print} function was added as a wrapper around \code{Rf_PrintValue}. - } - \item Changes in Rcpp Attributes: - \itemize{ - \item The \code{pkg_types.h} file is now included in \code{RcppExports.cpp} - if it is present in either the \code{inst/include} or \code{src}. - \item \code{sourceCpp} was modified to allow includes of local files - (e.g. \code{#include "foo.hpp"}). Implementation files (*.cc; *.cpp) corresponding - to local includes are also automatically built if they exist. - \item The generated attributes code was simplified with respect to - \code{RNGScope} and now uses \code{RObject} and its destructor rather than \code{SEXP} - protect/unprotect. - \item Support addition of the \code{rng} parameter in \code{Rcpp::export} - to suppress the otherwise automatic inclusion of \code{RNGScope} in - generated code. - \item Attributes code was made more robust and can e.g. no longer recurse. - \item Version 3.2 of the Rtools is now correctly detected as well. - \item Allow 'R' to come immediately after '***' for defining embedded R - code chunks in sourceCpp. - \item The attributes vignette has been updated with documentation - on new features added over the past several releases. - } - \item Changes in Rcpp tests: - \itemize{ - \item On Travis CI, all build dependencies are installed as binary - \code{.deb} packages resulting in faster tests. - } - } -} - -\section{Changes in Rcpp version 0.11.4 (2015-01-20)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item The \code{ListOf} class gains the \code{.attr} and - \code{.names} methods common to other Rcpp vectors. - \item The \code{[dpq]nbinom_mu()} scalar functions are now available via - the \code{R::} namespace when R 3.1.2 or newer is used. - \item Add an additional test for AIX before attempting to include \code{execinfo.h}. - \item \code{Rcpp::stop} now supports improved \code{printf}-like syntax - using the small tinyformat header-only library (following a similar - implementation in Rcpp11) - \item Pairlist objects are now protected via an additional \code{Shield<>} - as suggested by Martin Morgan on the rcpp-devel list. - \item Sorting is now prohibited at compile time for objects of type - \code{List}, \code{RawVector} and \code{ExpressionVector}. - \item Vectors now have a \code{Vector::const\_iterator} that is 'const correct' - thanks to fix by Romain following a bug report in rcpp-devel by Martyn Plummer. - \item The \code{mean()} sugar function now uses a more robust two-pass - method, and new unit tests for \code{mean()} were added at the same time. - \item The \code{mean()} and \code{var()} functions now support all core - vector types. - \item The \code{setequal()} sugar function has been corrected via - suggestion by Qiang Kou following a bug report by Søren Højsgaard. - \item The macros \code{major}, \code{minor}, and \code{makedev} no longer leak - in from the (Linux) system header \code{sys/sysmacros.h}. - \item The \code{push_front()} string function was corrected. - } - \item Changes in Rcpp Attributes: - \itemize{ - \item Only look for plugins in the package's namespace - (rather than entire search path). - \item Also scan header files for definitions of functions to be considerd - by Attributes. - \item Correct the regular expression for source files which are scanned. - } - \item Changes in Rcpp unit tests - \itemize{ - \item Added a new binary test which will load a pre-built package to - ensure that the Application Binary Interface (ABI) did not change; this - test will (mostly or) only run at Travis where we have reasonable control - over the platform running the test and can provide a binary. - \item New unit tests for sugar functions \code{mean}, \code{setequal} and - \code{var} were added as noted above. - } - \item Changes in Rcpp Examples: - \itemize{ - \item For the (old) examples \code{ConvolveBenchmarks} and \code{OpenMP}, - the respective \code{Makefile} was renamed to \code{GNUmakefile} to please - \code{R CMD check} as well as the CRAN Maintainers. - } - } -} - -\section{Changes in Rcpp version 0.11.3 (2014-09-27)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item The deprecation of \code{RCPP_FUNCTION_*} which was announced with - release 0.10.5 last year is proceeding as planned, and the file - \code{macros/preprocessor_generated.h} has been removed. - \item \code{Timer} no longer records time between steps, but times from - the origin. It also gains a \code{get_timers(int)} methods that - creates a vector of \code{Timer} that have the same origin. This is modelled - on the \code{Rcpp11} implementation and is more useful for situations where - we use timers in several threads. \code{Timer} also gains a constructor - taking a \code{nanotime_t} to use as its origin, and a \code{origin} method. - This can be useful for situations where the number of threads is not known - in advance but we still want to track what goes on in each thread. - \item A cast to \code{bool} was removed in the vector proxy code as - inconsistent behaviour between clang and g++ compilations was noticed. - \item A missing \code{update(SEXP)} method was added thanks to pull - request by Omar Andres Zapata Mesa. - \item A proxy for \code{DimNames} was added. - \item A \code{no_init} option was added for Matrices and Vectors. - \item The \code{InternalFunction} class was updated to work with - \code{std::function} (provided a suitable C++11 compiler is available) - via a pull request by Christian Authmann. - \item A \code{new_env()} function was added to \code{Environment.h} - \item The return value of range eraser for Vectors was fixed in a pull - request by Yixuan Qiu. - } - \item Changes in Rcpp Sugar: - \itemize{ - \item In \code{ifelse()}, the returned \code{NA} type was corrected for - \code{operator[]}. - } - \item Changes in Rcpp Attributes: - \itemize{ - \item Include LinkingTo in DESCRIPTION fields scanned to confirm that - C++ dependencies are referenced by package. - \item Add \code{dryRun} parameter to \code{sourceCpp}. - \item Corrected issue with relative path and R chunk use for \code{sourceCpp}. - } - \item Changes in Rcpp Documentation: - \itemize{ - \item The \code{Rcpp-FAQ} vignette was updated with respect to OS X issues. - \item A new entry in the \code{Rcpp-FAQ} clarifies the use of licenses. - \item Vignettes build results no longer copied to \code{/tmp} to please CRAN. - \item The Description in \code{DESCRIPTION} has been shortened. - } - \item Changes in Rcpp support functions: - \itemize{ - \item The \code{Rcpp.package.skeleton()} function will now use - \CRANpkg{pkgKitten} package, if available, to create a package which passes - \code{R CMD check} without warnings. A new \code{Suggests:} has been added - for \CRANpkg{pkgKitten}. - \item The \code{modules=TRUE} case for \code{Rcpp.package.skeleton()} has - been improved and now runs without complaints from \code{R CMD check} as well. - } - \item Changes in Rcpp unit test functions: - \itemize{ - \item Functions from the \CRANpkg{RUnit} package are now prefixed with \code{RUnit::} - \item The \code{testRcppModule} and \code{testRcppClass} sample packages - now pass \code{R CMD check --as-cran} cleanly with NOTES or WARNINGS - } - } -} - -\section{Changes in Rcpp version 0.11.2 (2014-06-06)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item Implicit conversions, e.g. between \code{NumericVector} and - \code{IntegerVector}, will now give warnings if you use - \code{\#define RCPP_WARN_ON_COERCE} before including the Rcpp - headers. - \item Templated \code{List} containers, \code{ListOf}, have been - introduced. When subsetting such containers, the return is assumed - to be of type T, allowing code such as - \code{ListOf x; NumericVector y = x[0] + x[1] + x[2]}. - \item In a number of instances, returned results are protected and/or cast - more carefully. - } - \item Changes in Rcpp Attributes - \itemize{ - \item Trailing line comments are now stripped by the attributes - parser. This allows the parser to handle C++ source files - containing comments inline with function arguments. - \item The \code{USE_CXX1X} environment variable is now defined by - the cpp11 plugin when R >= 3.1. Two additional plugins have been - added for use with C++0x (eg when using g++ 4.6.* as on Windows) - as well as C++1y for compilers beginning to support the next - revision of the standard; additional fallback is provided for - Windows. - \item \code{compileAttributes()} now also considers Imports: which - may suppress a warning when running \code{Rcpp.package.skeleton()}. - } - } -} - -\section{Changes in Rcpp version 0.11.1 (2014-03-13)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item Preserve backwards compatibility with \CRANpkg{Rcpp} 0.10.* by - allowing \code{RObject} extraction from vectors (or lists) of Rcpp - objects - \item Add missing default constructor to Reference class that was - omitted in the header-only rewrite - \item Fixes for \code{NA} and \code{NaN} handling of the - \code{IndexHash} class, as well as the vector \code{.sort()} - method. These fixes ensure that sugar functions depending on - \code{IndexHash} (i.e. \code{unique()}, \code{sort_unique()}, - \code{match()}) will now properly handle \code{NA} and \code{NaN} - values for numeric vectors. - \item \code{DataFrame::nrows} now more accurately mimics R's - internal behavior (checks the row.names attribute) - \item Numerous changes to permit compilation on the Solaris OS - \item Rcpp vectors gain a subsetting method -- it is now possible - to subset an Rcpp vector using \code{CharacterVector}s (subset - by name), \code{LogicalVector}s (logical subsetting), and - \code{IntegerVector}s (0-based index subsetting). Such subsetting - will also work with Rcpp sugar expressions, enabling expressions - such as \code{x[ x > 0]}. - \item Comma initialization (e.g. - \code{CharacterVector x = "a", "b", "c";}, has been disabled, as - it causes problems with the behavior of the \code{=} operator with - \code{Rcpp::List}s. Users who want to re-enable this functionality - can use \code{#define RCPP_COMMA_INITIALIZATION}, but be aware of - the above caveat. The more verbose - \code{CharacterVector x = CharacterVector::create("a", "b", "c")} - is preferred. - } - \item Changes in Rcpp Attributes - \itemize{ - \item Fix issue preventing packages with \code{Rcpp::interfaces} - attribute from compiling. - \item Fix behavior with attributes parsing of \code{::create} for default - arguments, and also allow constructors of a given size - (e.g. \code{NumericVector v = NumericVector(10))} gives a default - value of \code{numeric(10)} at the R level). Also make NAs preserve - type when exported to R (e.g. \code{NA_STRING} as a default argument - maps to \code{NA_character_} at the R level) - } - \item Changes in Rcpp modules - \itemize{ - \item Corrected the \code{un_pointer} implementation for \code{object} - } - } -} - -\section{Changes in Rcpp version 0.11.0 (2014-02-02)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item Functions provided/used by \CRANpkg{Rcpp} are now registered - with R and instantiated by client package alleviating the new for - explicit linking against \code{libRcpp} which is therefore no - longer created. - \item Updated the \code{Rcpp.package.skeleton()} function accordingly. - \item New class \code{StretchyList} for pair lists with fast addition of - elements at the front and back. This abstracts the 3 functions - \code{NewList}, \code{GrowList} and \code{Insert} used in various - packages and in parsers in R. - \item The function \code{dnt}, \code{pnt}, \code{qnt} sugar - functions were incorrectly expanding to the no-degree-of-freedoms - variant. - \item Unit tests for \code{pnt} were added. - \item The sugar table function did not handle NAs and NaNs properly - for numeric vectors. Fixed and tests added. - \item The internal coercion mechanism mapping numerics to strings has - been updated to better match \R (specifically with \code{Inf}, \code{-Inf}, - and \code{NaN}.) - \item Applied two bug fixes to Vector \code{sort()} and \code{RObject} - definition spotted and corrected by Kevin Ushey - \item New \code{checkUserInterrupt()} function that provides a C++ friendly - implementation of \code{R_CheckUserInterrupt}. - } - \item Changes in Rcpp attributes: - \itemize{ - \item Embedded R code chunks in sourceCpp are now executed within - the working directory of the C++ source file. - \item Embedded R code chunks in sourceCpp can now be disabled. - } - \item Changes in Rcpp documentation: - \itemize{ - \item The Rcpp-FAQ and Rcpp-package vignettes have been updated and expanded. - \item Vignettes are now typeset with grey background for code boxes. - \item The bibtex reference file has been update to reflexct - current package versions. - } - \item Changes in Rcpp unit tests: - \itemize{ - \item The file \code{tests/doRUnit.R} was rewritten following the - pattern deployed in \CRANpkg{RProtoBuf} which is due to Murray Stokely - \item The function \code{test()} was rewritten; it provides an - easy entry point to running unit tests of the installed package - } - } -} - -\section{Changes in Rcpp version 0.10.6 (2013-10-27)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item The function \code{exposeClass} takes a description of the - constructors, fields and methods to be exposed from a C++ - class, and writes C++ and R files in the package. Inherited - classes can be dealt with, but require data type information. - This approach avoids hand-coding module files. - \item Two missing \code{is<>()} templates for - \code{CharacterVector} and \code{CharacterMatrix} have been added, - and some tests for \code{is_na()} and \code{is_finite()} have been - corrected thanks to Thomas Tse. - } - \item Changes in R code: - \itemize{ - \item Export linking helper function \code{LdFlags} as well as - \code{RcppLdFlags}. - \item Function \code{Rcpp.package.skeleton()} no longer passes a - \code{namespace} argument on to \code{package.skeleton()} - } - \item Changes in R setup: - \itemize{ - \item Raise requirement for R itself to be version 3.0.0 or later - as needed by the vignette processing - } - \item Changes in Rcpp attributes: - \itemize{ - \item \code{sourceCpp} now correctly binds to Rtools 3.0 and 3.1 - } - } -} - -\section{Changes in Rcpp version 0.10.5 (2013-09-28)}{ - \itemize{ - \item Changes in R code: - \itemize{ - \item New R function \code{demangle} that calls the \code{DEMANGLE} macro. - \item New R function \code{sizeof} to query the byte size of a type. This - returns an object of S3 class \code{bytes} that has a \code{print} method - showing bytes and bits. - } - \item Changes in Rcpp API: - \itemize{ - \item Add \code{defined(__sun)} to lists of operating systems to - test for when checking for lack of \code{backtrace()} needed for - stack traces. - \item \code{as}, \code{as}, \code{as} and - \code{as} are now supported, when - T is a class exposed by modules, i.e. with \code{RCPP_EXPOSED_CLASS} - \item \code{DoubleVector} as been added as an alias to - \code{NumericVector} - \item New template function \code{is} to identify if an R object - can be seen as a \code{T}. For example \code{is(x)}. - This is a building block for more expressive dispatch in various places - (modules and attributes functions). - \item \code{wrap} can now handle more types, i.e. types that iterate over - \code{std::pair} where KEY can be converted to a - \code{String} and \code{VALUE} is either a primitive type (int, double) - or a type that wraps. Examples : - \itemize{ - \item \code{std::map} : we can make a String from an int, - and double is primitive - \item \code{boost::unordered_map >}: we can make - a String from a double and \code{std::vector} can wrap itself - } - Other examples of this are included at the end of the \code{wrap} unit test - file (\code{runit.wrap.R} and \code{wrap.cpp}). - \item \code{wrap} now handles containers of classes handled by modules. e.g. - if you expose a class \code{Foo} via modules, then you can wrap - \code{vector}, ... An example is included in the \code{wrap} unit test - file - \item \code{RcppLdFlags()}, often used in \code{Makevars} files of - packages using \pkg{Rcpp}, is now exported from the package namespace. - } - \item Changes in Attributes: - \itemize{ - \item Objects exported by a module (i.e. by a \code{RCPP_MODULE} call - in a file that is processed by \code{sourceCpp}) are now directly - available in the environment. We used to make the module object - available, which was less useful. - \item A plugin for \code{openmp} has been added to support use of OpenMP. - \item \code{Rcpp::export} now takes advantage of the more flexible - \code{as<>}, handling constness and referenceness of the input types. - For users, it means that for the parameters of function exported by modules, - we can now use references, pointers and const versions of them. - The file \code{Module.cpp} file has an example. - \item{No longer call non-exported functions from the tools package} - \item{No longer search the inline package as a fallback when loading - plugins for the the \code{Rcpp::plugins} attribute}. - } - \item Changes in Modules: - \itemize{ - \item We can now expose functions and methods that take - \code{T&} or \code{const T&} as arguments. In these situations - objects are no longer copied as they used to be. - } - \item Changes in sugar: - \itemize{ - \item \code{is_na} supports classes \code{DatetimeVector} and - \code{DateVector} - } - \item Changes in Rcpp documentation: - \itemize{ - \item The vignettes have been moved from \code{inst/doc/} to the - \code{vignettes} directory which is now preferred. - \item The appearance of the vignettes has been refreshed by - switching to the Bistream Charter font, and microtype package. - } - \item Deprecation of \code{RCPP_FUNCTION_*}: - \itemize{ - \item The macros from the \code{preprocessor_generated.h} file - have been deprecated. They are still available, but they print a - message in addition to their expected behavior. - \item The macros will be permanently removed in the first \pkg{Rcpp} - release after July 2014. - \item Users of these macros should start replacing them with more - up-to-date code, such as using 'Rcpp attributes' or 'Rcpp modules'. - } - } -} - -\section{Changes in Rcpp version 0.10.4 (2013-06-23)}{ - \itemize{ - \item Changes in R code: None beyond those detailed for Rcpp Attributes - \item Changes in Rcpp attributes: - \itemize{ - \item Fixed problem whereby the interaction between the gc and the - RNGScope destructor could cause a crash. - \item Don't include package header file in generated C++ interface - header files. - \item Lookup plugins in \pkg{inline} package if they aren't found - within the \pkg{Rcpp} package. - \item Disallow compilation for files that don't have extensions - supported by R CMD SHLIB - } - \item Changes in Rcpp API: - \itemize{ - \item The \code{DataFrame::create} set of functions has been reworked - to just use \code{List::create} and feed to the \code{DataFrame} - constructor - \item The \code{operator-()} semantics for \code{Date} and - \code{Datetime} are now more inline with standard C++ behaviour; - with thanks to Robin Girard for the report. - \item RNGScope counter now uses unsigned long rather than int. - \item \code{Vector<*>::erase(iterator, iterator)} was fixed. Now - it does not remove the element pointed by last (similar to what is - done on stl types and what was intended initially). Reported on - Rcpp-devel by Toni Giorgino. - \item Added equality operator between elements of - \code{CharacterVector}s. - } - \item Changes in Rcpp sugar: - \itemize{ - \item New function \code{na_omit} based on the StackOverflow thread - \url{http://stackoverflow.com/questions/15953768/} - \item New function \code{is_finite} and \code{is_infinite} that - reproduces the behavior of R's \code{is.finite} and - \code{is.infinite} functions - } - \item Changes in Rcpp build tools: - \itemize{ - \item Fix by Martyn Plummer for Solaris in handling of - \code{SingleLogicalResult}. - \item The \code{src/Makevars} file can now optionally override the - path for \code{/usr/bin/install_name_tool} which is used on OS X. - \item Vignettes are trying harder not to be built in parallel. - } - \item Changes in Rcpp documentation: - \itemize{ - \item Updated the bibliography in \code{Rcpp.bib} (which is also - sourced by packages using Rcpp). - \item Updated the \code{THANKS} file. - } - \item Planned Deprecation of \code{RCPP_FUNCTION_*}: - \itemize{ - \item The set of macros \code{RCPP_FUNCTION_} etc ... from the - \code{preprocessor_generated.h} file will be deprecated in the next version - of \pkg{Rcpp}, i.e they will still be available but will generate some - warning in addition to their expected behavior. - \item In the first release that is at least 12 months after this announcement, the - macros will be removed from \pkg{Rcpp}. - \item Users of these macros (if there are any) should start replacing them - with more up to date code, such as using Rcpp attributes or Rcpp - modules. - } - } -} - -\section{Changes in Rcpp version 0.10.3 (2013-03-23)}{ - \itemize{ - \item Changes in R code: - \itemize{ - \item Prevent build failures on Windowsn when Rcpp is installed - in a library path with spaces (transform paths in the same manner - that R does before passing them to the build system). - } - \item Changes in Rcpp attributes: - \itemize{ - \item Rcpp modules can now be used with \code{sourceCpp} - \item Standalone roxygen chunks (e.g. to document a class) are now - transposed into RcppExports.R - \item Added \code{Rcpp::plugins} attribute for binding - directly to inline plugins. Plugins can be registered using - the new \code{registerPlugin} function. - \item Added built-in \code{cpp11} plugin for specifying - the use of C++11 in a translation unit - \item Merge existing values of build related environment - variables for sourceCpp - \item Add global package include file to RcppExports.cpp - if it exists - \item Stop with an error if the file name passed to - \code{sourceCpp} has spaces in it - \item Return invisibly from void functions - \item Ensure that line comments invalidate block comments when - parsing for attributes - \item Eliminated spurious empty hello world function definition - in Rcpp.package.skeleton - } - \item Changes in Rcpp API: - \itemize{ - \item The very central use of R API R_PreserveObject and - R_ReleaseObject has been replaced by a new system based on the - functions Rcpp_PreserveObject, Rcpp_ReleaseObject and Rcpp_ReplaceObject - which shows better performance and is implemented using a generic vector - treated as a stack instead of a pairlist in the R - implementation. However, as this preserve / release code is still - a little rough at the edges, a new #define is used (in config.h) - to disable it for now. - \item Platform-dependent code in Timer.cpp now recognises a few - more BSD variants thanks to contributed defined() test suggestions - \item Support for wide character strings has been added throughout the - API. In particular String, CharacterVector, wrap and as are aware of - wide character strings - } - } -} - -\section{Changes in Rcpp version 0.10.2 (2012-12-21)}{ - \itemize{ - \item Changes in Rcpp API: - \itemize{ - \item Source and header files were reorganized and consolidated so - that compile time are now significantly lower - \item Added additional check in \code{Rstreambuf} deletetion - \item Added support for \code{clang++} when using \code{libc++}, - and for anc \code{icpc} in \code{std=c++11} mode, thanks to a - patch by Yan Zhou - \item New class \code{Rcpp::String} to facilitate working with a single - element of a character vector - \item New utility class sugar::IndexHash inspired from Simon - Urbanek's fastmatch package - \item Implementation of the equality operator between two Rcomplex - \item \code{RNGScope} now has an internal counter that enables it - to be safely used multiple times in the same stack frame. - \item New class \code{Rcpp::Timer} for benchmarking - } - \item Changes in Rcpp sugar: - \itemize{ - \item More efficient version of \code{match} based on \code{IndexHash} - \item More efficient version of \code{unique} base on \code{IndexHash} - \item More efficient version of \code{in} base on \code{IndexHash} - \item More efficient version of \code{duplicated} base on \code{IndexHash} - \item More efficient version of \code{self_match} base on \code{IndexHash} - \item New function \code{collapse} that implements paste(., collapse= "" ) - } - \item Changes in Rcpp attributes: - \itemize{ - \item Use code generation rather than modules to implement - \code{sourceCpp} and \code{compileAttributes} (eliminates - problem with exceptions not being able to cross shared library - boundaries on Windows) - \item Exported functions now automatically establish an \code{RNGScope} - \item Functions exported by \code{sourceCpp} now directly - reference the external function pointer rather than rely on - dynlib lookup - \item On Windows, Rtools is automatically added to the PATH - during \code{sourceCpp} compilations - \item Diagnostics are printed to the console if \code{sourceCpp} - fails and C++ development tools are not installed - \item A warning is printed if when \code{compileAttributes} detects - \code{Rcpp::depends} attributes in source files that are not - matched by Depends/LinkingTo entries in the package DESCRIPTION - } - } -} - -\section{Changes in Rcpp version 0.10.1 (2012-11-26)}{ - \itemize{ - \item Changes in Rcpp sugar: - \itemize{ - \item New functions: \code{setdiff}, \code{union_}, \code{intersect} - \code{setequal}, \code{in}, \code{min}, \code{max}, \code{range}, - \code{match}, \code{table}, \code{duplicated} - \item New function: \code{clamp} which combines pmin and pmax, e.g. - clamp( a, x, b) is the same as pmax( b, pmin(x, a) ) - \item New function: \code{self_match} which implements something - similar to \code{match( x, unique( x ) )} - } - \item Changes in Rcpp API: - \itemize{ - \item The \code{Vector} template class (hence \code{NumericVector} - ...) get the \code{is_na} and the \code{get_na} static methods. - \item New helper class \code{no_init} that can be used to - create a vector without initializing its data, e.g. : - \code{ IntegerVector out = no_init(n) ; } - \item New exception constructor requiring only a message; \code{stop} - function to throw an exception - \item \code{DataFrame} gains a \code{nrows} method - } - \item Changes in Rcpp attributes: - \itemize{ - \item Ability to embed R code chunks (via specially formatted - block comments) in C++ source files. - \item Allow specification of argument defaults for exported functions. - \item New scheme for more flexible mixing of generated and user composed - C++ headers. - \item Print warning if no export attributes are found in source file. - \item Updated vignette with additional documentation on exposing - C++ interfaces from packages and signaling errors. - } - \item Changes in Rcpp modules: - \itemize{ - \item Enclose .External invocations in \code{BEGIN_RCPP}/\code{END_RCPP} - } - \item Changes in R code : - \itemize{ - \item New function \code{areMacrosDefined} - \item Additions to \code{Rcpp.package.skeleton}: - \itemize{ - \item \code{attributes} parameter to generate a version of - \code{rcpp_hello_world} that uses \code{Rcpp::export}. - \item \code{cpp_files} parameter to provide a list of C++ - files to include the in the \code{src} directory of the package. - } - } - \item Miscellaneous changes: - \itemize{ - \item New example 'pi simulation' using R and C++ via Rcpp attributes - } - } -} -\section{Changes in Rcpp version 0.10.0 (2012-11-13)}{ - \itemize{ - \item Support for C++11 style attributes (embedded in comments) to enable - use of C++ within interactive sessions and to automatically generate module - declarations for packages: - \itemize{ - \item Rcpp::export attribute to export a C++ function to R - \item \code{sourceCpp()} function to source exported functions from a file - \item \code{cppFunction()} and \code{evalCpp()} functions for inline declarations - and execution - \item \code{compileAttribtes()} function to generate Rcpp modules from - exported functions within a package - \item Rcpp::depends attribute for specifying additional build - dependencies for \code{sourceCpp()} - \item Rcpp::interfaces attribute to specify the external bindings - \code{compileAttributes()} should generate (defaults to R-only but a - C++ include file using R_GetCCallable can also be generated) - \item New vignette "Rcpp-attribute" - } - \item Rcpp modules feature set has been expanded: - \itemize{ - \item Functions and methods can now return objects from classes that - are exposed through modules. This uses the make_new_object template - internally. This feature requires that some class traits are declared - to indicate Rcpp's \code{wrap}/\code{as} system that these classes are covered - by modules. The macro RCPP_EXPOSED_CLASS and RCPP_EXPOSED_CLASS_NODECL - can be used to declared these type traits. - \item Classes exposed through modules can also be used as parameters - of exposed functions or methods. - \item Exposed classes can declare factories with ".factory". A factory - is a c++ function that returns a pointer to the target class. It is - assumed that these objects are allocated with new on the factory. On the - R side, factories are called just like other constructors, with the - "new" function. This feature allows an alternative way to construct - objects. - \item "converter" can be used to declare a way to convert an object - of a type to another type. This gets translated to the appropriate - "as" method on the R side. - \item Inheritance. A class can now declare that it inherits from - another class with the .derives( "Parent" ) notation. As a result - the exposed class gains methods and properties (fields) from its - parent class. - } - \item New sugar functions: - \itemize{ - \item \code{which_min} implements which.min. Traversing the sugar expression - and returning the index of the first time the minimum value is found. - \item \code{which_max} idem - \item \code{unique} uses unordered_set to find unique values. In particular, - the version for CharacterVector is found to be more efficient than - R's version - \item \code{sort_unique} calculates unique values and then sorts them. - } - \item Improvements to output facilities: - \itemize{ - \item Implemented \code{sync()} so that flushing output streams works - \item Added \code{Rcerr} output stream (forwarding to - \code{REprintf}) - } - \item Provide a namespace 'R' for the standalone Rmath library so - that Rcpp users can access those functions too; also added unit tests - \item Development releases sets variable RunAllRcppTests to yes to - run all tests (unless it was alredy set to 'no'); CRAN releases do - not and still require setting -- which helps with the desired CRAN - default of less testing at the CRAN server farm. - } -} - -\section{Changes in Rcpp version 0.9.15 (2012-10-13)}{ - \itemize{ - \item Untangling the clang++ build issue about the location of the - exceptions header by directly checking for the include file -- an - approach provided by Martin Morgan in a kindly contributed patch - as unit tests for them. - \item The \code{Date} and \code{Datetime} types now correctly - handle \code{NA}, \code{NaN} and \code{Inf} representation; the - \code{Date} type switched to an internal representation via \code{double} - \item Added \code{Date} and \code{Datetime} unit tests for the new - features - \item An additional \code{PROTECT} was added for parsing exception - messages before returning them to R, following a report by Ben North - } -} - -\section{Changes in Rcpp version 0.9.14 (2012-09-30)}{ - \itemize{ - \item Added new Rcpp sugar functions trunc(), round() and signif(), as well - as unit tests for them - \item Be more conservative about where we support clang++ and the inclusion - of exception_defines.h and prevent this from being attempted on OS X - where it failed for clang 3.1 - \item Corrected a typo in Module.h which now again permits use of finalizers - \item Small correction for (unexported) bib() function (which provides a path - to the bibtex file that ships with Rcpp) - \item Converted NEWS to NEWS.Rd - } -} -\section{Changes in Rcpp version 0.9.13 (2012-06-28)}{ - \itemize{ - \item Truly corrected Rcpp::Environment class by having default constructor - use the global environment, and removing the default argument of - global environment from the SEXP constructor - \item Added tests for clang++ version to include bits/exception_defines.h - for versions 3.0 or higher (similar to g++ 4.6.0 or later), needed to - include one particular exceptions header - \item Made more regression tests conditional on the RunAllRcppTests to come - closer to the CRAN mandate of running tests in sixty seconds - \item Updated unit test wrapper tests/doRUnit.R as well as unitTests/runTests.R - } -} -\section{Changes in Rcpp version 0.9.12 (2012-06-23)}{ - \itemize{ - \item Corrected Rcpp::Environment class by removing (empty) ctor following - rev3592 (on May 2) where default argument for ctor was moved - \item Unit testing now checks for environment variable RunAllRcppTests being - set to "yes"; otherwise some tests are skipped. This is arguably not - the right thing to do, but CRAN maintainers insist on faster tests. - \item Unit test wrapper script runTests.R has new option --allTests to set - the environment variable - \item The cleanup script now also considers inst/unitTests/testRcppClass/src - } -} -\section{Changes in Rcpp version 0.9.11 (2012-06-22)}{ - \itemize{ - \item New member function for vectors (and lists etc) containsElementNamed() - which returns a boolean indicating if the given element name is present - \item Updated the Rcpp.package.skeleton() support for Rcpp modules by - carrying functions already present from the corresponding unit test - which was also slightly expanded; and added more comments to the code - \item Rcpp modules can now be loaded via loadRcppModules() from .onLoad(), - or via loadModule("moduleName") from any R file - \item Extended functionality to let R modify C++ clases imported via modules - documented in help(setRcppClass) - \item Support compilation in Cygwin thanks to a patch by Dario Buttari - \item Extensions to the Rcpp-FAQ and the Rcpp-modules vignettes - \item The minium version of R is now 2.15.1 which is required for some of - the Rcpp modules support - } -} -\section{Changes in Rcpp version 0.9.10 (2012-02-16)}{ - \itemize{ - \item Rearrange headers so that Rcpp::Rcout can be used by RcppArmadillo et al - \item New Rcpp sugar function mapply (limited to two or three input vectors) - \item Added custom version of the Rcpp sugar diff function for numeric vectors - skipping unncesserry checks for NA - \item Some internal code changes to reflect changes and stricter requirements - in R CMD check in the current R-devel versions - \item Corrected fixed-value initialization for IntegerVector (with thanks to - Gregor Kastner for spotting this) - \item New Rcpp-FAQ entry on simple way to set compiler option for cxxfunction - } -} -\section{Changes in Rcpp version 0.9.9 (2012-12-25)}{ - \itemize{ - \item Reverting the 'int64' changes from release 0.9.8 which adversely - affect packages using Rcpp: We will re-apply the 'int64' changes in a - way which should cooperate more easily with 'long' and 'unsigned long'. - \item Unit test output directory fallback changed to use Rcpp.Rcheck - \item Conditioned two unit tests to not run on Windows where they now break - whereas they passed before, and continue to pass on other OSs - } -} -\section{Changes in Rcpp version 0.9.8 (2011-12-21)}{ - \itemize{ - \item wrap now handles 64 bit integers (int64_t, uint64_t) and containers - of them, and Rcpp now depends on the int64 package (also on CRAN). - This work has been sponsored by the Google Open Source Programs - Office. - \item Added setRcppClass() function to create extended reference classes - with an interface to a C++ class (typically via Rcpp Module) which - can have R-based fields and methods in addition to those from the C++. - \item Applied patch by Jelmer Ypma which adds an output stream class - 'Rcout' not unlike std::cout, but implemented via Rprintf to - cooperate with R and its output buffering. - \item New unit tests for pf(), pnf(), pchisq(), pnchisq() and pcauchy() - \item XPtr constructor now checks for corresponding type in SEXP - \item Updated vignettes for use with updated highlight package - \item Update linking command for older fastLm() example using external - Armadillo - } -} -\section{Changes in Rcpp version 0.9.7 (2011-09-29)}{ - \itemize{ - \item Applied two patches kindly provided by Martyn Plummer which provide - support for compilation on Solaris using the SunPro compiler - \item Minor code reorganisation in which exception specifiers are removed; - this effectively only implements a run-time (rather than compile-time) - check and is generally seen as a somewhat depreated C++ idiom. Thanks - to Darren Cook for alerting us to this issue. - \item New example 'OpenMPandInline.r' in the OpenMP/ directory, showing how - easily use OpenMP by modifying the RcppPlugin output - \item New example 'ifelseLooped.r' showing Rcpp can accelerate loops that may - be difficult to vectorise due to dependencies - \item New example directory examples/Misc/ regrouping the new example as - well as the fibonacci example added in Rcpp 0.9.6 - \item New Rcpp-FAQ example warning of lossy conversion from 64-bit long - integer types into a 53-bit mantissa which has no clear fix yet. - \item New unit test for accessing a non-exported function from a namespace - } -} -\section{Changes in Rcpp version 0.9.6 (2011-07-26)}{ - \itemize{ - \item Added helper traits to facilitate implementation of the RcppEigen - package: The is_eigen_base traits identifies if a class derives from - EigenBase using SFINAE; and new dispatch layer was added to wrap() to - help RcppEigen - \item XPtr now accepts a second template parameter, which is a function - taking a pointer to the target class. This allows the developper to - supply his/her own finalizer. The template parameter has a default - value which retains the original behaviour (calling delete on the - pointer) - \item New example RcppGibbs, extending Sanjog Misra's Rcpp illustration of - Darren Wilkinson's comparison of MCMC Gibbs Sampler implementations; - also added short timing on Normal and Gaussian RNG draws between Rcpp - and GSL as R's rgamma() is seen to significantly slower - \item New example on recursively computing a Fibonacci number using Rcpp and - comparing this to R and byte-compiled R for a significant speed gain - } -} -\section{Changes in Rcpp version 0.9.5 (2011-07-05)}{ - \itemize{ - \item New Rcpp-FAQ examples on using the plugin maker for inline's - cxxfunction(), and on setting row and column names for matrices - \item New sugar functions: mean, var, sd - \item Minor correction and extension to STL documentation in Rcpp-quickref - \item wrap() is now resilient to NULL pointers passed as in const char * - \item loadRcppModules() gains a "direct" argument to expose the module instead - of exposing what is inside it - \item Suppress a spurious warning from R CMD check on packages created with - Rcpp.package.skeleton(..., module=TRUE) - \item Some fixes and improvements for Rcpp sugar function 'rlnorm()' - \item Beginnings of new example using OpenMP and recognising user interrupts - } -} -\section{Changes in Rcpp version 0.9.4 (2011-04-12)}{ - \itemize{ - \item New R function "loadRcppModules" to load Rcpp modules automatically - from a package. This function must be called from the .onLoad function - and works with the "RcppModules" field of the package's DESCRIPTION file - \item The Modules example wrapped the STL std::vector received some editing - to disambiguate some symbols the newer compilers did not like - \item Coercing of vectors of factors is now done with an explicit callback - to R's "as.character()" as Rf_coerceVector no longer plays along - \item A CITATION file for the published JSS paper has been added, and - references were added to Rcpp-package.Rd and the different vignettes - } -} -\section{Changes in Rcpp version 0.9.3 (2011-04-05)}{ - \itemize{ - \item Fixed a bug in which modules code was not behaving when compiled - twice as can easily happen with inline'ed version - \item Exceptions code includes exception_defines.h only when g++ is 4.5 or - younger as the file no longer exists with g++-4.6 - \item The documentation Makefile now uses the $R_HOME environment variable - \item The documentation Makefile no longer calls clean in the all target - \item C++ conformance issue found by clang/llvm addressed by re-ordering - declarations in grow.h as unqualified names must be declared before - they are used, even when used within templates - \item The 'long long' typedef now depends on C++0x being enabled as this - was not a feature in C++98; this suppresses a new g++-4.5 warning - \item The Rcpp-introduction vignette was updated to the forthcoming JSS paper - } -} -\section{Changes in Rcpp version 0.9.2 (2011-02-23)}{ - \itemize{ - \item The unitTest runit.Module.client.package.R is now skipped on older OS - X releases as it triggers a bug with g++ 4.2.1 or older; OS X 10.6 is - fine but as it no longer support ppc we try to accomodate 10.5 too - Thanks to Simon Urbanek for pinning this down and Baptiste Auguie - and Ken Williams for additonal testing - \item RcppCommon.h now recognises the Intel Compiler thanks to a short - patch by Alexey Stukalov; this turns off Cxx0x and TR1 features too - \item Three more setup questions were added to the Rcpp-FAQ vignette - \item One question about RcppArmadillo was added to the Rcpp-FAQ vignette - } -} -\section{Changes in Rcpp version 0.9.1 (2011-02-14)}{ - \itemize{ - \item A number of internal changes to the memory allocation / protection of - temporary objects were made---with a heartfelt "Thank You!" to both - Doug Bates for very persistent debugging of Rcpp modules code, and to - Luke Tierney who added additional memory allocation debugging tools - to R-devel (which will be in R 2.13.0 and may also be in R 2.12.2) - \item Removed another GNU Make-specific variable from src/Makevars in order - to make the build more portable; this was noticed on FreeBSD - \item On *BSD, do not try to compute a stack trace but provide file and - line number (which is the same behaviour as implemented in Windows) - \item Fixed an int conversion bug reported by Daniel Sabanes Bove on r-devel, - added unit test as well - \item Added unit tests for complex-typed vectors (thanks to Christian Gunning) - \item Expanded the Rcpp-quickref vignette (with thanks to Christian Gunning) - \item Additional examples were added to the Rcpp-FAQ vignette - } -} -\section{Changes in Rcpp version 0.9.0 (2010-12-19)}{ - \itemize{ - \item The classic API was factored out into its own package RcppClassic which - is released concurrently with this version. - \item If an object is created but not initialized, attempting to use - it now gives a more sensible error message (by forwarding an - Rcpp::not_initialized exception to R). - \item SubMatrix fixed, and Matrix types now have a nested ::Sub typedef. - \item New unexported function SHLIB() to aid in creating a shared library on - the command-line or in Makefile (similar to CxxFlags() / LdFlags()). - \item Module gets a seven-argument ctor thanks to a patch from Tama Ma. - \item The (still incomplete) QuickRef vignette has grown thanks to a patch - by Christian Gunning. - \item Added a sprintf template intended for logging and error messages. - \item Date::getYear() corrected (where addition of 1900 was not called for); - corresponding change in constructor from three ints made as well. - \item Date() and Datetime() constructors from string received a missing - conversion to int and double following strptime. The default format - string for the Datetime() strptime call was also corrected. - \item A few minor fixes throughout, see ChangeLog. - } -} -\section{Changes in Rcpp version 0.8.9 (2010-11-27)}{ - \itemize{ - \item Many improvements were made in 'Rcpp modules': - - exposing multiple constructors - - overloaded methods - - self-documentation of classes, methods, constructors, fields and - functions. - - new R function "populate" to facilitate working with modules in - packages. - - formal argument specification of functions. - - updated support for Rcpp.package.skeleton. - - constructors can now take many more arguments. - \item The 'Rcpp-modules' vignette was updated as well and describe many - of the new features - \item New template class Rcpp::SubMatrix and support syntax in Matrix - to extract a submatrix: - NumericMatrix x = ... ; - // extract the first three columns - SubMatrix y = x( _ , Range(0,2) ) ; - // extract the first three rows - SubMatrix y = x( Range(0,2), _ ) ; - // extract the top 3x3 sub matrix - SubMatrix y = x( Range(0,2), Range(0,2) ) ; - \item Reference Classes no longer require a default constructor for - subclasses of C++ classes - \item Consistently revert to using backticks rather than shell expansion - to compute library file location when building packages against Rcpp - on the default platforms; this has been applied to internal test - packages as well as CRAN/BioC packages using Rcpp - } -} -\section{Changes in Rcpp version 0.8.8 (2010-11-01)}{ - \itemize{ - \item New syntactic shortcut to extract rows and columns of a Matrix. - x(i,_) extracts the i-th row and x(_,i) extracts the i-th column. - \item Matrix indexing is more efficient. However, faster indexing is - disabled if g++ 4.5.0 or later is used. - \item A few new Rcpp operators such as cumsum, operator=(sugar) - \item Variety of bug fixes: - - column indexing was incorrect in some cases - - compilation using clang/llvm (thanks to Karl Millar for the patch) - - instantation order of Module corrected - - POSIXct, POSIXt now correctly ordered for R 2.12.0 - } -} -\section{Changes in Rcpp version 0.8.7 (2010-10-15)}{ - \itemize{ - \item As of this version, Rcpp depends on R 2.12 or greater as it interfaces - the new reference classes (see below) and also reflects the POSIXt - class reordering both of which appeared with R version 2.12.0 - \item new Rcpp::Reference class, that allows internal manipulation of R - 2.12.0 reference classes. The class exposes a constructor that takes - the name of the target reference class and a field(string) method - that implements the proxy pattern to get/set reference fields using - callbacks to the R operators "$" and "$<-" in order to preserve the - R-level encapsulation - \item the R side of the preceding item allows methods to be written in R as - per ?ReferenceClasses, accessing fields by name and assigning them - using "<<-". Classes extracted from modules are R reference classes. - They can be subclassed in R, and/or R methods can be defined using - the $methods(...) mechanism. - \item internal performance improvements for Rcpp sugar as well as an added - 'noNA()' wrapper to omit tests for NA values -- see the included - examples in inst/examples/convolveBenchmarks for the speedups - \item more internal performance gains with Functions and Environments - } -} -\section{Changes in Rcpp version 0.8.6 (2010-09-09)}{ - \itemize{ - \item new macro RCPP_VERSION and Rcpp_Version to allow conditional compiling - based on the version of Rcpp - #if defined(RCPP_VERSION) && RCPP_VERSION >= Rcpp_Version(0,8,6) - #endif - \item new sugar functions for statistical distributions (d-p-q-r functions) - with distributions : unif, norm, gamma, chisq, lnorm, weibull, logis, - f, pois, binom, t, beta. - \item new ctor for Vector taking size and function pointer so that for example - NumericVector( 10, norm_rand ) - generates a N(0,1) vector of size 10 - \item added binary operators for complex numbers, as well as sugar support - \item more sugar math functions: sqrt, log, log10, exp, sin, cos, ... - \item started new vignette Rcpp-quickref : quick reference guide of Rcpp API - (still work in progress) - \item various patches to comply with solaris/suncc stricter standards - \item minor enhancements to ConvolutionBenchmark example - \item simplified src/Makefile to no longer require GNU make; packages using - Rcpp still do for the compile-time test of library locations - } -} -\section{Changes in Rcpp version 0.8.5 (2010-07-25)}{ - \itemize{ - \item speed improvements. Vector::names, RObject::slot have been improved - to take advantage of R API functions instead of callbacks to R - \item Some small updates to the Rd-based documentation which now points to - content in the vignettes. Also a small formatting change to suppress - a warning from the development version of R. - \item Minor changes to Date() code which may reenable SunStudio builds - } -} -\section{Changes in Rcpp version 0.8.4 (2010-07-09)}{ - \itemize{ - \item new sugar vector functions: rep, rep_len, rep_each, rev, head, tail, - diag - \item sugar has been extended to matrices: The Matrix class now extends the - Matrix_Base template that implements CRTP. Currently sugar functions - for matrices are: outer, col, row, lower_tri, upper_tri, diag - \item The unit tests have been reorganised into fewer files with one call - each to cxxfunction() (covering multiple tests) resulting in a - significant speedup - \item The Date class now uses the same mktime() replacement that R uses - (based on original code from the timezone library by Arthur Olson) - permitting wide date ranges on all operating systems - \item The FastLM example has been updated, a new benchmark based on the - historical Longley data set has been added - \item RcppStringVector now uses std::vector internally - \item setting the .Data slot of S4 objects did not work properly - } -} -\section{Changes in Rcpp version 0.8.3 (2010-06-27)}{ - \itemize{ - \item This release adds Rcpp sugar which brings (a subset of) the R syntax - into C++. This supports : - - binary operators : <,>,<=,>=,==,!= between R vectors - - arithmetic operators: +,-,*,/ between compatible R vectors - - several functions that are similar to the R function of the same name: - abs, all, any, ceiling, diff, exp, ifelse, is_na, lapply, pmin, pmax, - pow, sapply, seq_along, seq_len, sign - Simple examples : - // two numeric vector of the same size - NumericVector x ; - NumericVector y ; - NumericVector res = ifelse( x < y, x*x, -(y*y) ) ; - // sapply'ing a C++ function - double square( double x )\{ return x*x ; \} - NumericVector res = sapply( x, square ) ; - Rcpp sugar uses the technique of expression templates, pioneered by the - Blitz++ library and used in many libraries (Boost::uBlas, Armadillo). - Expression templates allow lazy evaluation of expressions, which - coupled with inlining generates very efficient code, very closely - approaching the performance of hand written loop code, and often - much more efficient than the equivalent (vectorized) R code. - Rcpp sugar is curently limited to vectors, future releases will - include support for matrices with sugar functions such as outer, etc ... - Rcpp sugar is documented in the Rcpp-sugar vignette, which contains - implementation details. - \item New helper function so that "Rcpp?something" brings up Rcpp help - \item Rcpp Modules can now expose public data members - \item New classes Date, Datetime, DateVector and DatetimeVector with proper - 'new' API integration such as as(), wrap(), iterators, ... - \item The so-called classic API headers have been moved to a subdirectory - classic/ This should not affect client-code as only Rcpp.h was ever - included. - \item RcppDate now has a constructor from SEXP as well - \item RcppDateVector and RcppDatetimeVector get constructors from int - and both const / non-const operator(int i) functions - \item New API class Rcpp::InternalFunction that can expose C++ functions - to R without modules. The function is exposed as an S4 object of - class C++Function - } -} -\section{Changes in Rcpp version 0.8.2 (2010-06-09)}{ - \itemize{ - \item Bug-fix release for suncc compiler with thanks to Brian Ripley for - additional testing. - } -} -\section{Changes in Rcpp version 0.8.1 (2010-06-08)}{ - \itemize{ - \item This release adds Rcpp modules. An Rcpp module is a collection of - internal (C++) functions and classes that are exposed to R. This - functionality has been inspired by Boost.Python. - Modules are created internally using the RCPP_MODULE macro and - retrieved in the R side with the Module function. This is a preview - release of the module functionality, which will keep improving until - the Rcpp 0.9.0 release. - The new vignette "Rcpp-modules" documents the current feature set of - Rcpp modules. - \item The new vignette "Rcpp-package" details the steps involved in making a - package that uses Rcpp. - \item The new vignette "Rcpp-FAQ" collects a number of frequently asked - questions and answers about Rcpp. - \item The new vignette "Rcpp-extending" documents how to extend Rcpp - with user defined types or types from third party libraries. Based on - our experience with RcppArmadillo - \item Rcpp.package.skeleton has been improved to generate a package using - an Rcpp module, controlled by the "module" argument - \item Evaluating a call inside an environment did not work properly - \item cppfunction has been withdrawn since the introduction of the more - flexible cxxfunction in the inline package (0.3.5). Rcpp no longer - depends on inline since many uses of Rcpp do not require inline at - all. We still use inline for unit tests but this is now handled - locally in the unit tests loader runTests.R. - Users of the now-withdrawn function cppfunction can redefine it as: - cppfunction <- function(...) cxxfunction( ..., plugin = "Rcpp" ) - \item Support for std::complex was incomplete and has been enhanced. - \item The methods XPtr::getTag and XPtr::getProtected are deprecated, - and will be removed in Rcpp 0.8.2. The methods tag() and prot() should - be used instead. tag() and prot() support both LHS and RHS use. - \item END_RCPP now returns the R Nil values; new macro VOID_END_RCPP - replicates prior behabiour - } -} -\section{Changes in Rcpp version 0.8.0 (2010-05-17)}{ - \itemize{ - \item All Rcpp headers have been moved to the inst/include directory, - allowing use of 'LinkingTo: Rcpp'. But the Makevars and Makevars.win - are still needed to link against the user library. - \item Automatic exception forwarding has been withdrawn because of - portability issues (as it did not work on the Windows platform). - Exception forwarding is still possible but is now based on explicit - code of the form: - try \{ - // user code - \} catch( std::exception& __ex__)\{ - forward_exception_to_r( __ex___ ) ; - Alternatively, the macro BEGIN_RCPP and END_RCPP can use used to enclose - code so that it captures exceptions and forward them to R. - BEGIN_RCPP - // user code - END_RCPP - \item new __experimental__ macros - The macros RCPP_FUNCTION_0, ..., RCPP_FUNCTION_65 to help creating C++ - functions hiding some code repetition: - RCPP_FUNCTION_2( int, foobar, int x, int y)\{ - return x + y ; - The first argument is the output type, the second argument is the - name of the function, and the other arguments are arguments of the - C++ function. Behind the scenes, the RCPP_FUNCTION_2 macro creates an - intermediate function compatible with the .Call interface and handles - exceptions - Similarly, the macros RCPP_FUNCTION_VOID_0, ..., RCPP_FUNCTION_VOID_65 - can be used when the C++ function to create returns void. The generated - R function will return R_NilValue in this case. - RCPP_FUNCTION_VOID_2( foobar, std::string foo )\{ - // do something with foo - The macro RCPP_XP_FIELD_GET generates a .Call compatible function that - can be used to access the value of a field of a class handled by an - external pointer. For example with a class like this: - class Foo\{ - public: - int bar ; - RCPP_XP_FIELD_GET( Foo_bar_get, Foo, bar ) ; - RCPP_XP_FIELD_GET will generate the .Call compatible function called - Foo_bar_get that can be used to retrieved the value of bar. - The macro RCPP_FIELD_SET generates a .Call compatible function that - can be used to set the value of a field. For example: - RCPP_XP_FIELD_SET( Foo_bar_set, Foo, bar ) ; - generates the .Call compatible function called "Foo_bar_set" that - can be used to set the value of bar - The macro RCPP_XP_FIELD generates both getter and setter. For example - RCPP_XP_FIELD( Foo_bar, Foo, bar ) - generates the .Call compatible Foo_bar_get and Foo_bar_set using the - macros RCPP_XP_FIELD_GET and RCPP_XP_FIELD_SET previously described - The macros RCPP_XP_METHOD_0, ..., RCPP_XP_METHOD_65 faciliate - calling a method of an object that is stored in an external pointer. For - example: - RCPP_XP_METHOD_0( foobar, std::vector , size ) - creates the .Call compatible function called foobar that calls the - size method of the std::vector class. This uses the Rcpp::XPtr< - std::vector > class. - The macros RCPP_XP_METHOD_CAST_0, ... is similar but the result of - the method called is first passed to another function before being - wrapped to a SEXP. For example, if one wanted the result as a double - RCPP_XP_METHOD_CAST_0( foobar, std::vector , size, double ) - The macros RCPP_XP_METHOD_VOID_0, ... are used when calling the - method is only used for its side effect. - RCPP_XP_METHOD_VOID_1( foobar, std::vector, push_back ) - Assuming xp is an external pointer to a std::vector, this could - be called like this : - .Call( "foobar", xp, 2L ) - \item Rcpp now depends on inline (>= 0.3.4) - \item A new R function "cppfunction" was added which invokes cfunction from - inline with focus on Rcpp usage (enforcing .Call, adding the Rcpp - namespace, set up exception forwarding). cppfunction uses BEGIN_RCPP - and END_RCPP macros to enclose the user code - \item new class Rcpp::Formula to help building formulae in C++ - \item new class Rcpp::DataFrame to help building data frames in C++ - \item Rcpp.package.skeleton gains an argument "example_code" and can now be - used with an empty list, so that only the skeleton is generated. It - has also been reworked to show how to use LinkingTo: Rcpp - \item wrap now supports containers of the following types: long, long double, - unsigned long, short and unsigned short which are silently converted - to the most acceptable R type. - \item Revert to not double-quote protecting the path on Windows as this - breaks backticks expansion used n Makevars.win etc - \item Exceptions classes have been moved out of Rcpp classes, - e.g. Rcpp::RObject::not_a_matrix is now Rcpp::not_a_matrix - } -} -\section{Changes in Rcpp version 0.7.12 (2010-04-16)}{ - \itemize{ - \item Undo shQuote() to protect Windows path names (which may contain - spaces) as backticks use is still broken; use of $(shell ...) works - } -} -\section{Changes in Rcpp version 0.7.11 (2010-03-26)}{ - \itemize{ - \item Vector<> gains a set of templated factory methods "create" which - takes up to 20 arguments and can create named or unnamed vectors. - This greatly facilitates creating objects that are returned to R. - \item Matrix now has a diag() method to create diagonal matrices, and - a new constructor using a single int to create square matrices - \item Vector now has a new fill() method to propagate a single value - \item Named is no more a class but a templated function. Both interfaces - Named(.,.) and Named(.)=. are preserved, and extended to work also on - simple vectors (through Vector<>::create) - \item Applied patch by Alistair Gee to make ColDatum more robust - \item Fixed a bug in Vector that caused random behavior due to the lack of - copy constructor in the Vector template - } -} -\section{Changes in Rcpp version 0.7.10 (2010-03-15)}{ - \itemize{ - \item new class Rcpp::S4 whose constructor checks if the object is an S4 - object - \item maximum number of templated arguments to the pairlist function, the - DottedPair constructor, the Language constructor and the Pairlist - constructor has been updated to 20 (was 5) and a script has been - added to the source tree should we want to change it again - \item use shQuote() to protect Windows path names (which may contain spaces) - } -} -\section{Changes in Rcpp version 0.7.9 (2010-03-12)}{ - \itemize{ - \item Another small improvement to Windows build flags - \item bugfix on 64 bit platforms. The traits classes (wrap_type_traits, etc) - used size_t when they needed to actually use unsigned int - \item fixed pre gcc 4.3 compatibility. The trait class that was used to - identify if a type is convertible to another had too many false - positives on pre gcc 4.3 (no tr1 or c++0x features). fixed by - implementing the section 2.7 of "Modern C++ Design" book. - } -} -\section{Changes in Rcpp version 0.7.8 (2010-03-09)}{ - \itemize{ - \item All vector classes are now generated from the same template class - Rcpp::Vector where RTYPE is one of LGLSXP, RAWSXP, STRSXP, - INTSXP, REALSXP, CPLXSXP, VECSXP and EXPRSXP. typedef are still - available : IntegerVector, ... All vector classes gain methods - inspired from the std::vector template : push_back, push_front, - erase, insert - \item New template class Rcpp::Matrix deriving from - Rcpp::Vector. These classes have the same functionality - as Vector but have a different set of constructors which checks - that the input SEXP is a matrix. Matrix<> however does/can not - guarantee that the object will allways be a matrix. typedef - are defined for convenience: Matrix is IntegerMatrix, etc... - \item New class Rcpp::Row that represents a row of a matrix - of the same type. Row contains a reference to the underlying - Vector and exposes a nested iterator type that allows use of - STL algorithms on each element of a matrix row. The Vector class - gains a row(int) method that returns a Row instance. Usage - examples are available in the runit.Row.R unit test file - \item New class Rcpp::Column that represents a column of a - matrix. (similar to Rcpp::Row). Usage examples are - available in the runit.Column.R unit test file - \item The Rcpp::as template function has been reworked to be more - generic. It now handles more STL containers, such as deque and - list, and the genericity can be used to implement as for more - types. The package RcppArmadillo has examples of this - \item new template class Rcpp::fixed_call that can be used in STL algorithms - such as std::generate. - \item RcppExample et al have been moved to a new package RcppExamples; - src/Makevars and src/Makevars.win simplified accordingly - \item New class Rcpp::StringTransformer and helper function - Rcpp::make_string_transformer that can be used to create a function - that transforms a string character by character. For example - Rcpp::make_string_transformer(tolower) transforms each character - using tolower. The RcppExamples package has an example of this. - \item Improved src/Makevars.win thanks to Brian Ripley - \item New examples for 'fast lm' using compiled code: - - using GNU GSL and a C interface - - using Armadillo (http://arma.sf.net) and a C++ interface - Armadillo is seen as faster for lack of extra copying - \item A new package RcppArmadillo (to be released shortly) now serves - as a concrete example on how to extend Rcpp to work with a modern - C++ library such as the heavily-templated Armadillo library - \item Added a new vignette 'Rcpp-introduction' based on a just-submitted - overview article on Rcpp - } -} -\section{Changes in Rcpp version 0.7.7 (2010-02-14)}{ - \itemize{ - \item new template classes Rcpp::unary_call and Rcpp::binary_call - that facilitates using R language calls together - with STL algorithms. - \item fixed a bug in Language constructors taking a string as their - first argument. The created call was wrong. - } -} -\section{Changes in Rcpp version 0.7.6 (2010-02-12)}{ - \itemize{ - \item SEXP_Vector (and ExpressionVector and GenericVector, a.k.a List) now - have methods push_front, push_back and insert that are templated - \item SEXP_Vector now has int- and range-valued erase() members - \item Environment class has a default constructor (for RInside) - \item SEXP_Vector_Base factored out of SEXP_Vector (Effect. C++ #44) - \item SEXP_Vector_Base::iterator added as well as begin() and end() - so that STL algorithms can be applied to Rcpp objects - \item CharacterVector gains a random access iterator, begin() and end() to - support STL algorithms; iterator dereferences to a StringProxy - \item Restore Windows build; successfully tested on 32 and 64 bit; - \item Small fixes to inst/skeleton files for bootstrapping a package - \item RObject::asFoo deprecated in favour of Rcpp::as - } -} -\section{Changes in Rcpp version 0.7.5 (2010-02-08)}{ - \itemize{ - \item wrap has been much improved. wrappable types now are : - - primitive types : int, double, Rbyte, Rcomplex, float, bool - - std::string - - STL containers which have iterators over wrappable types: - (e.g. std::vector, std::deque, std::list, etc ...). - - STL maps keyed by std::string, e.g std::map - - classes that have implicit conversion to SEXP - - classes for which the wrap template if fully or partly specialized - This allows composition, so for example this class is wrappable: - std::vector< std::map > (if T is wrappable) - \item The range based version of wrap is now exposed at the Rcpp:: - level with the following interface : - Rcpp::wrap( InputIterator first, InputIterator last ) - This is dispatched internally to the most appropriate implementation - using traits - \item a new namespace Rcpp::traits has been added to host the various - type traits used by wrap - \item The doxygen documentation now shows the examples - \item A new file inst/THANKS acknowledges the kind help we got from others - \item The RcppSexp has been removed from the library. - \item The methods RObject::asFoo are deprecated and will be removed - in the next version. The alternative is to use as. - \item The method RObject::slot can now be used to get or set the - associated slot. This is one more example of the proxy pattern - \item Rcpp::VectorBase gains a names() method that allows getting/setting - the names of a vector. This is yet another example of the - proxy pattern. - \item Rcpp::DottedPair gains templated operator<< and operator>> that - allow wrap and push_back or wrap and push_front of an object - \item Rcpp::DottedPair, Rcpp::Language, Rcpp::Pairlist are less - dependent on C++0x features. They gain constructors with up - to 5 templated arguments. 5 was choosed arbitrarily and might - be updated upon request. - \item function calls by the Rcpp::Function class is less dependent - on C++0x. It is now possible to call a function with up to - 5 templated arguments (candidate for implicit wrap) - \item added support for 64-bit Windows (thanks to Brian Ripley and Uwe Ligges) - } -} -\section{Changes in Rcpp version 0.7.4 (2010-01-30)}{ - \itemize{ - \item matrix-like indexing using operator() for all vector - types : IntegerVector, NumericVector, RawVector, CharacterVector - LogicalVector, GenericVector and ExpressionVector. - \item new class Rcpp::Dimension to support creation of vectors with - dimensions. All vector classes gain a constructor taking a - Dimension reference. - \item an intermediate template class "SimpleVector" has been added. All - simple vector classes are now generated from the SimpleVector - template : IntegerVector, NumericVector, RawVector, CharacterVector - LogicalVector. - \item an intermediate template class "SEXP_Vector" has been added to - generate GenericVector and ExpressionVector. - \item the clone template function was introduced to explicitely - clone an RObject by duplicating the SEXP it encapsulates. - \item even smarter wrap programming using traits and template - meta-programming using a private header to be include only - RcppCommon.h - \item the as template is now smarter. The template now attempts to - build an object of the requested template parameter T by using the - constructor for the type taking a SEXP. This allows third party code - to create a class Foo with a constructor Foo(SEXP) to have - as for free. - \item wrap becomes a template. For an object of type T, wrap uses - implicit conversion to SEXP to first convert the object to a SEXP - and then uses the wrap(SEXP) function. This allows third party - code creating a class Bar with an operator SEXP() to have - wrap for free. - \item all specializations of wrap : wrap, wrap< vector > - use coercion to deal with missing values (NA) appropriately. - \item configure has been withdrawn. C++0x features can now be activated - by setting the RCPP_CXX0X environment variable to "yes". - \item new template r_cast to facilitate conversion of one SEXP - type to another. This is mostly intended for internal use and - is used on all vector classes - \item Environment now takes advantage of the augmented smartness - of as and wrap templates. If as makes sense, one can - directly extract a Foo from the environment. If wrap makes - sense then one can insert a Bar directly into the environment. - Foo foo = env["x"] ; /* as is used */ - Bar bar ; - env["y"] = bar ; /* wrap is used */ - \item Environment::assign becomes a template and also uses wrap to - create a suitable SEXP - \item Many more unit tests for the new features; also added unit tests - for older API - } -} -\section{Changes in Rcpp version 0.7.3 (2010-01-21)}{ - \itemize{ - \item New R function Rcpp.package.skeleton, modelled after - utils::package.skeleton to help creating a package with support - for Rcpp use. - \item indexing is now faster for simple vectors due to inlining of - the operator[] and caching the array pointer - \item The class Rcpp::VectorBase was introduced. All vector classes - derive from it. The class handles behaviour that is common - to all vector types: length, names, etc ... - \item exception forwarding is extended to compilers other than GCC - but default values are used for the exception class - and the exception message, because we don't know how to do it. - \item Improved detection of C++0x capabilities - \item Rcpp::Pairlist gains a default constructor - \item Rcpp::Environment gains a new_child method to create a new - environment whose parent is this - \item Rcpp::Environment::Binding gains a templated implicit - conversion operator - \item Rcpp::ExpressionVector gains an eval method to evaluate itself - \item Rcpp::ExpressionVector gains a constructor taking a std::string - representing some R code to parse. - \item Rcpp::GenericVector::Proxy gains an assignment operator to deal - with Environment::Proxy objects - \item Rcpp::LdFlags() now defaults to static linking OS X, as it already - did on Windows; this default can be overridden. - } -} -\section{Changes in Rcpp version 0.7.2 (2010-01-12)}{ - \itemize{ - \item a new benchmark was added to the examples directory - around the classic convolution example from - Writing R extensions to compare C and C++ implementations - \item Rcpp::CharacterVector::StringProxy gains a += operator - \item Rcpp::Environment gains an operator[](string) to get/set - objects from the environment. operator[] returns an object - of class Rcpp::Environment::Binding which implements the proxy - pattern. Inspired from Item 30 of 'More Effective C++' - \item Rcpp::Pairlist and Rcpp::Language gain an operator[](int) - also using the proxy pattern - \item Rcpp::RObject.attr can now be used on the rhs or the lhs, to get - or set an attribute. This also uses the proxy pattern - \item Rcpp::Pairlist and Rcpp::Language gain new methods push_back - replace, length, size, remove, insert - \item wrap now returns an object of a suitable class, not just RObject - anymore. For example wrap( bool ) returns a LogicalVector - \item Rcpp::RObject gains methods to deal with S4 objects : isS4, - slot and hasSlot - \item new class Rcpp::ComplexVector to manage complex vectors (CPLXSXP) - \item new class Rcpp::Promise to manage promises (PROMSXP) - \item new class Rcpp::ExpressionVector to manage expression vectors - (EXPRSXP) - \item new class Rcpp::GenericVector to manage generic vectors, a.k.a - lists (VECSXP) - \item new class Rcpp::IntegerVector to manage integer vectors (INTSXP) - \item new class Rcpp::NumericVector to manage numeric vectors (REALSXP) - \item new class Rcpp::RawVector to manage raw vectors (RAWSXP) - \item new class Rcpp::CharacterVector to manage character vectors (STRSXP) - \item new class Rcpp::Function to manage functions - (CLOSXP, SPECIALSXP, BUILTINSXP) - \item new class Rcpp::Pairlist to manage pair lists (LISTSXP) - \item new class Rcpp::Language to manage calls (LANGSXP) - \item new specializations of wrap to deal with std::initializer lists - only available with GCC >= 4.4 - \item new R function Rcpp:::capabilities that can query if various - features are available : exception handling, variadic templates - initializer lists - \item new set of functions wrap(T) converting from T to RObject - \item new template function as that can be used to convert a SEXP - to type T. Many specializations implemented to deal with - C++ builtin and stl types. Factored out of RObject - \item new class Rcpp::Named to deal with named with named objects - in a pairlist, or a call - \item new class Rcpp::Symbol to manage symbols (SYMSXP) - \item The garbage collection has been improved and is now automatic - and hidden. The user needs not to worry about it at all. - \item Rcpp::Environment(SEXP) uses the as.environment R function - \item Doxygen-generated documentation is no longer included as it is both - too large and too volatile. Zipfiles are provided on the website. - } -} -\section{Changes in Rcpp version 0.7.1 (2010-01-02)}{ - \itemize{ - \item Romain is now a co-author of Rcpp - \item New base class Rcpp::RObject replace RcppSexp (which is provided for - backwards compatibility) - \item RObject has simple wrappers for object creation and conversion to SEXP - \item New classes Rcpp::Evaluator and Rcpp::Environment for expression - evaluation and environment access, respectively - \item New class Rcpp::XPtr for external pointers - \item Enhanced exception handling allows for trapping of exceptions outside - of try/catch blocks - \item Namespace support with a new namespace 'Rcpp' - \item Unit tests for most of the new classes, based on the RUnit package - \item Inline support now provided by the update inline package, so a new - Depends on 'inline (>= 0.3.4)' replaces the code in that was - temporarily in Rcpp - } -} -\section{Changes in Rcpp version 0.7.0 (2009-12-19)}{ - \itemize{ - \item Inline support via a modified version of 'cfunction' from Oleg - Sklyar's 'inline' package: simple C++ programs can now be compiled, - linked and loaded automagically from the R prompt, including support - for external packages. Also works on Windows (with R-tools installed) - \item New examples for the inline support based on 'Intro to HPC' tutorials - \item New type RcppSexp for simple int, double, std::string scalars and vectors - \item Every class is now in its own header and source file - \item Fix to RcppParams.Rd thanks to Frank S. Thomas - \item RcppVersion.R removed as redundant given DESCRIPTION and read.dcf() - \item Switched to R_PreserveObject and R_ReleaseObject for RcppSexp with - thanks to Romain - \item Licensing changed from LGPL 2.1 (or later) to GPL 2 (or later), file - COPYING updated - } -} -\section{Changes in Rcpp version 0.6.8 (2009-11-19)}{ - \itemize{ - \item Several classes now split off into their own header and source files - \item New header file RcppCommon.h regrouping common defines and includes - \item Makevars\{,.win\} updated to reflect src/ reorg - } -} -\section{Changes in Rcpp version 0.6.7 (2009-11-08)}{ - \itemize{ - \item New class RcppList for simple lists and data structures of different - types and dimensions, useful for RProtoBuf project on R-Forge - \item Started to split classes into their own header and source files - \item Added short README file about history and status - \item Small documentation markup fix thanks to Kurt; updated doxygen docs - \item New examples directory functionCallback/ for R function passed to C++ - and being called - } -} -\section{Changes in Rcpp version 0.6.6 (2009-08-03)}{ - \itemize{ - \item Updated Doxygen documentation - \item RcppParams class gains a new exists() member function - } -} -\section{Changes in Rcpp version 0.6.5 (2009-04-01)}{ - \itemize{ - \item Small OS X build correction using R_ARCH variable - \item Include LGPL license as file COPYING - } -} -\section{Changes in Rcpp version 0.6.4 (2009-03-01)}{ - \itemize{ - \item Use std:: namespace throughout instead of 'using namespace std' - \item Define R_NO_REMAP so that R provides Rf_length() etc in lieu of length() - to minimise clashes with other projects having similar functions - \item Include Doxygen documentation, and Doxygen configuration file - \item Minor Windows build fix (with thanks to Uwe and Simon) - } -} -\section{Changes in Rcpp version 0.6.3 (2009-01-09)}{ - \itemize{ - \item OS X build fix with thanks to Simon - \item Added 'view-only' classes for int and double vector and matrix clases - as well as string vector classses, kindly suggsted / provided by - David Reiss - \item Add two shorter helper functions Rcpp:::CxxFlags() and - Rcpp:::LdFlags() for compilation and linker flags - } -} -\section{Changes in Rcpp version 0.6.2 (2008-12-02)}{ - \itemize{ - \item Small but important fix for Linux builds in Rcpp:::RcppLdFlags() - } -} -\section{Changes in Rcpp version 0.6.1 (2008-11-30)}{ - \itemize{ - \item Now src/Makevars replaces src/Makefile, this brings proper OS X - multi-arch support with thanks to Simon - \item Old #ifdef statements related to QuantLib removed; Rcpp is now - decoupled from QuantLib headers yet be used by RQuantLib - \item Added RcppLdPath() to return the lib. directory patch and on Linux - the rpath settings - \item Added new RcppVectorExample() - \item Augmented documentation on usage in Rcpp-package.Rd - } -} -\section{Changes in Rcpp version 0.6.0 (2008-11-05)}{ - \itemize{ - \item New maintainer, taking over RcppTemplate (which has been without an - update since Nov 2006) under its initial name Rcpp - \item New files src/Makefile\{,.win\} including functionality from both - configure and RcppSrc/Makefile; we now build two libraries, one for - use by the package which also runs the example, and one for users to - link against, and removed src/Makevars.in - \item Files src/Rcpp.\{cpp,h\} moved in from ../RcppSrc - \item Added new class RcppDatetime corresponding to POSIXct in with full - support for microsecond time resolution between R and C++ - \item Several new manual pages added - \item Removed configure\{,.in,.win\} as src/Makefile* can handle this more - easily - \item Minor cleanup and reformatting for DESCRIPTION, Date: now uses - svn:keyword Date property - \item Renamed RcppTemplateVersion to RcppVersion, deleted RcppDemo - \item Directory demo/ removed as vignette("RcppAPI") is easier and more - reliable to show vignette documentation - \item RcppTemplateDemo() removed from R/zzz.R, vignette("RcppAPI") is easier; - man/RcppTemplateDemo.Rd removed as well - \item Some more code reindentation and formatting to R default arguments, - some renamed from RcppTemplate* to Rcpp* - \item Added footnote onto titlepage of inst/doc/RcppAPI.\{Rnw,pdf\} about how - this document has not (yet) been updated along with the channges made - } -} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/R/Rcpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/R/Rcpp deleted file mode 100644 index 3b65e3c..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/R/Rcpp +++ /dev/null @@ -1,27 +0,0 @@ -# File share/R/nspackloader.R -# Part of the R package, http://www.R-project.org -# -# Copyright (C) 1995-2012 The R Core Team -# -# This program is free software; you can redistribute it and/or modify -# it under the terms of the GNU General Public License as published by -# the Free Software Foundation; either version 2 of the License, or -# (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# A copy of the GNU General Public License is available at -# http://www.r-project.org/Licenses/ - -local({ - info <- loadingNamespaceInfo() - pkg <- info$pkgname - ns <- .getNamespace(as.name(pkg)) - if (is.null(ns)) - stop("cannot find namespace environment for ", pkg, domain = NA); - dbbase <- file.path(info$libname, pkg, "R", pkg) - lazyLoad(dbbase, ns, filter = function(n) n != ".__NAMESPACE__.") -}) diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/R/Rcpp.rdb b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/R/Rcpp.rdb deleted file mode 100644 index 1a6eca6..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/R/Rcpp.rdb and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/R/Rcpp.rdx b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/R/Rcpp.rdx deleted file mode 100644 index 286a381..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/R/Rcpp.rdx and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/README b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/README deleted file mode 100644 index 25fd423..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/README +++ /dev/null @@ -1,53 +0,0 @@ - -History -======= - -Rcpp continues and extends earlier work by Dominick Samperi which he initially -contributed directly into the RQuantLib package. Then, during 2005 and 2006, -several releases were made as CRAN packages, first under the name Rcpp and -later under the name RcppTemplate. However, both packages were left -abandonded after November 2006. Later, in November 2009, two brief releases -were made and abandonded immediately afterwards. - -Due to the continued use of Rcpp both within RQuantLib and in other projects, -Dirk took over maintenance in November 2008 and added some extensions which -are documented in the NEWS file, the ChangeLog and the included annoucements -of the major releases. - -With Romain joining development in late 2009, Rcpp development accelerated. A -richer, more powerful API has been developped to replace the previous API that -we now call 'classic Rcpp API'. The 'classic Rcpp API' has been factored -out of Rcpp in its own package 'RcppClassic'. - - -Documentation -============= - -Several so-called 'vignette' pdf documents are included which provide - - o an introduction; - - o answers to frequently asked question; - - o documentation about how to use Rcpp in other R packages; - - o documentation of modules (to access C++ classes and functions); - - o documentation of sugar (expressive C++ code for vectors and matrices); - - o notes about extending Rcpp; - - o results from the hundreds of unit tests. - -The CRAN package RcppExamples provides additionnal documentation and -examples. - - -Contact -======= - -Rcpp is in active and open development, and new contributors are invited to -follow the development on GitHub. The rcpp-devel project mailing list is the main -venue for discussions about Rcpp. - - -- Dirk Eddelbuettel and Romain Francois diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/THANKS b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/THANKS deleted file mode 100644 index b0cce9a..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/THANKS +++ /dev/null @@ -1,33 +0,0 @@ - -In alphabetical order: - -Baptiste Auguie for additional OS X testing -Dario Buttari for a patch permitting compilation under Cygwin -Darren Cook for suggesting to remove exception specifiers -Laurent Gautier for helpful discussions on R internals -Alistair Gee for a patch making ColDatum more robust -Toni Giorgino for a bug report concerning erase(iter, iter) -Robin Girard for a pointing out that operator+ on Date types was wrong -Christian Gunning for a documentation + unit tests patches and reporting bugs -Rainer Hurling for help debugging builds issues on FreeBSD -Gregor Kastner for noticing a bug in IntegerVector initialization -Glenn Lawyer for sending in documentation patches -Gong-Yi Liao for a corrected compile-time test for long long variables -Uwe Ligges for help with Windows (32 and 64 bit) build issues -Tama Ma for a patch that extends Module constructors -Omar Andres Zapata Mesa for spotting a missing update() in InternalFunction_Impl -Karl Millar for a patch helping with a non-g++ compiler -Anirban Mukherjee for reporting more clang++ warnings we had not seen -Ben North for a bug report and patch concerning iterators -Martyn Plummer for help and patches regarding Solaris build issues -David Reiss for the first-ever contributed patch (Rcpp*View) -Brian Ripley for help with Win64 + Solaris build issues -Dominick Samperi for starting what is now in the RcppClassic package -Oleg Sklyar for the incredibly cool inline package -Alexey Stukalov for a support enabling Intel Compiler 12.0 support -Luke Tierney for helpful discussions on R internals -Thomas Tse for several patches with small corrections -Simon Urbanek for help on OS X build issues and with R internals -Ken Williams for additional OS X testing -Jelmer Ypma for contributing the Rcout iostreams class patch -Yan Zhou for patches improving C++11 and compiler support diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.10.0.txt b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.10.0.txt deleted file mode 100644 index 6d5beeb..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.10.0.txt +++ /dev/null @@ -1,188 +0,0 @@ - - -===== Summary ===== - -Version 0.10.0 of the Rcpp package is now on CRAN and its mirrors. - -This new release brings a number of new features, as well as extensions to -existing features, to the package. Several key aspects are highlighted -below, and further details can be found in the NEWS and ChangeLog files which -are included in the package. - - - -===== Overview ===== - -Rcpp is an R package and associated C++ library for seamless integration -between C++ and R. - -It has been described in a recent paper in the Journal of Statistical -Software (Vol 40, Issue 08) which is also included in the package as the -"Rcpp-introduction" pdf vignette. - -As of late 2012, Rcpp is used by over 80 other CRAN packages making it the -most widely-used language interface for R. - -Several key features of the new 0.10.0 release are described below. - - - -===== Rcpp attributes ===== - -Rcpp attributes are a new feature of Rcpp version 0.10.0 that provide -infrastructure for seamless language bindings between R and C++. With -attributes we hope to eliminate the need to write boilerplate conversion -and marshaling code, make it much easier to use C++ within interactive -R sessions, and reduce the learning curve associated with using C++ -and R together. - -Rcpp attributes derive their syntax from C++11 style attributes and -are included in C++ source files using specially formatted comments. -For example, the following source file includes the definition of -a fibonacci function with an Rcpp::export attribute included -immediately above the function definition: - -#include -using namespace Rcpp; - -// [[Rcpp::export]] -int fibonacci(const int x) { - if (x < 2) - return x; - else - return (fibonacci(x - 1)) + fibonacci(x - 2); -} - -The export attribute indicates that we'd like the function to be callable -from R. We can now "source" this C++ file at the R prompt and then call -the function as follows: - -R> sourceCpp("fibonacci.cpp") -R> fibonacci(20) -[1] 6765 - -Rcpp attributes build upon Rcpp modules (described in another vignette in the -package), as well as the automatic type converters Rcpp::as<>() and Rcpp::wrap. -The converters can already be used for a wide variety of standard C and C++ -types, and can also be adapted to other C++ types and libraries as described -in the Rcpp-extending vignette. - -Rcpp attributes and their supporting functions include: - - - Rcpp::export attribute to export a C++ function to R - - sourceCpp function to source exported functions from a file - - cppFunction and evalCpp functions for inline declarations and execution - - Rcpp::depends attribute for specifying additional build dependencies - for sourceCpp - -Attributes can also be used for package development via the `compileAttributes` -function, which generates an Rcpp module for all exported functions within -an R package. - -More details are provided in the new vignette Rcpp-attributes. We also intend -to provide further illustrations via our blogs following the release. - - - -===== Rcpp modules ===== - -Rcpp modules provide an easy way to expose C++ functions and classes to R using -a declarative syntax. We declare which functions and which classes we want to -make available to R and modules takes care of automatically (via the compiler, -through template deduction ...) creating the interface code between the C++ -code and R. - -Rcpp modules have been extended for the new release. A brief -summary of new key features is: - - - inheritance: A class can now declare that it inherits from another class; - the exposed class gains methods and properties (fields) from its parent class. - - Functions and methods can now return objects from classes that are exposed - through modules. The macro RCPP_EXPOSED_CLASS and RCPP_EXPOSED_CLASS_NODECL - can be used to declared the required type traits. - - Classes exposed through modules can also be used as parameters of exposed - functions or methods. - - Exposed classes can declare factories, i.e. a C++ function returning a - pointer to the target class, providing an alternative way to construct - objects. - - "converter" can be used to declare a way to convert ("cast") an object of - a type to another type. This is translated at the R level in terms of an "as" - method. - -We intend to provide example packages using these new features in the near future. - - - -===== New sugar functions ===== - -Rcpp sugar provides "syntactic sugar" familiar to R programmers at the C++ -level, including a large number of vectorised functions. In this release, we -added - - which_min() and which_max() returning the index of the first object - matching the condition - - unique() and sort_unique() - - - -===== New I/O facilities ===== - -The Rcpp::Rcout object now supports the std::flush manipulator, which calls -R_FlushConsole. A new object Rcpp::Rcerr has been added with passes content -for error messages to REprintf(). - - - -===== New namespace "R::" for Rmath functions ===== - -A side-effect of Rcpp sugar providing vectorised d/p/q/r functions for the -various statistical distribution was that the scalar variants of these -functions (available from Rmath.h) were masked behind a Rf_ prefix. -Previously, one had to call ::Rf_pnorm5() to compute pnorm() -- but now a -cleaner interface R::pnorm() is available. Unit tests were added as well. - - - -===== Links ===== - -Rcpp main page: - http://dirk.eddelbuettel.com/code/rcpp.html - -R-forge project page: - http://r-forge.r-project.org/projects/rcpp/ - -Dirk's blog section about Rcpp - Rcpp: http://dirk.eddelbuettel.com/blog/code/rcpp/ - -Romain's blog section about Rcpp: - http://romainfrancois.blog.free.fr/index.php?category/R-package/Rcpp - -RStudio blog: - http://blog.rstudio.org - -Google+: - https://plus.google.com/b/107029540907667241299/107029540907667241299/posts - -Facebook: - http://www.facebook.com/pages/Rcpp/213047595425775 - -Twitter: - https://twitter.com/eddelbuettel - https://twitter.com/romain_francois - - - -===== Support ===== - -Questions about Rcpp should be directed to the Rcpp-devel mailing list - https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel - -While we prefer the mailing list, StackOverflow has also become a frequently -used resource under the [rcpp] tag: - http://stackoverflow.com/questions/tagged/rcpp - - -Dirk Eddelbuettel, Romain Francois, Doug Bates, John Chambers and JJ Allaire -November 2012 - - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.11.0.txt b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.11.0.txt deleted file mode 100644 index 3b0a35e..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.11.0.txt +++ /dev/null @@ -1,136 +0,0 @@ - - -===== Summary ===== - -Version 0.11.0 of the Rcpp package is now on CRAN and its mirrors. - -This new release brings a number of new features, most noticably a simplified -build system, as well as improvements to existing features and bugfixes. - -Complete details of the changes implemented between the last announcement for -version 0.10.0 and this new can be found in the NEWS and ChangeLog files -which are included in the package. - - - -===== Overview ===== - -Rcpp is an R package and associated C++ library for seamless integration -between C++ and R. - -It has been described in a Journal of Statistical Software (2011, Vol 40, -Issue 08) paper (also included in the package as the "Rcpp-introduction" pdf -vignette) and a book "Seamless R and C++ Integration with Rcpp" (2013, -Springer, useR! Series). - -As of early 2014, Rcpp is used by over 160 other CRAN packages. - -Several key features of the new 0.11.0 release are described below. - - - -===== One-time rebuild required ===== - -Because of the simplified linking scheme detailed in the next section, and -the corresponding removal of the libRcpp.* library, all packages currently -using Rcpp need to be reinstalled. - -We provide a simple helper script at -https://github.com/RcppCore/rcpp-logs/blob/master/scripts/showReverseRcppDepends.r -to identidy which of your currently-installed packages use Rcpp, and need to -be rebuilt / reinstalled. - - - -===== Simpler Building with Rcpp ===== - -Thanks to the 'LinkingTo:' directive, R already instructed the compiler where -to fine header files when writing code with Rcpp. The package now uses the -registration facilities in R (see Section 5.4 in Writing R Extensions). - -With just an 'Imports: Rcpp' in DESCRIPTION along with an explicit import -statement in the NAMESPACE file such 'importFrom(Rcpp, evalCpp)' all required -Rcpp code will be properly instantiated without any explicit linking. [ Note -that just using 'import(Rcpp)' is not sufficient, but any exported C++ -identifier should do -- evalCpp is nice and short. ] - -This means that the package no longer provides a user-facing library -libRcpp.so (or libRcpp.dylib or libRcpp.dll). This also implies that a -one-time rebuild is needed as alluded to in the previous section. - -The key benefit is that many package should no longer require the files -src/Makevars and src/Makevars.win in order to link with Rcpp. Mny packages -will be able to retire these files. The exception, of course, is the case -where a package links against an external library as eg the RcppArmadillo -package> Here, the LAPACK / BLAS / Fortran libraries still need to be -linked. However, the corresponding values are also provided by R and the -expression becomes a simple 'PKG_LIBS=$(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS)'. - - - -===== Rcpp attributes ===== - -Rcpp attributes were a key innovation in the 0.10.0; they have matured -further and have now become the standard way to build code with Rcpp. See -the dedicated vignette for details. - - - -==== C++11 Support ===== - -R 3.1.0, to be released in a few month, will permit compilation using C++11, -the newest C++ standard -- including for packages going to CRAN. Rcpp had -already supported 'local' builds using C++11 since version 0.10.3, simply add - - [[Rcpp::plugins(cpp11)]] - -and Rcpp attributes takes care of the rest. - - - -===== Memory management ===== - -A number of internal data structures have been rewritten. - - - -===== Links ===== - -Rcpp site: - http://www.rcpp.org - -Rcpp Gallery: - http://gallery.rcpp.org - -Dirk's Rcpp page: - http://dirk.eddelbuettel.com/code/rcpp.html - -GitHub page: - https://github.com/RcppCore/Rcpp - -R-forge project page: - http://r-forge.r-project.org/projects/rcpp/ - -Google+: - https://plus.google.com/b/107029540907667241299/107029540907667241299/posts - - - -===== Support ===== - -Questions about Rcpp should be directed to the Rcpp-devel mailing list - https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel - -While we prefer the mailing list, StackOverflow has also become a frequently -used resource under the [rcpp] tag: - http://stackoverflow.com/questions/tagged/rcpp - - - -On behalf of the Rcpp Core team, - - Dirk Eddelbuettel - February 2014 - - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.6.0.txt b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.6.0.txt deleted file mode 100644 index b741158..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.6.0.txt +++ /dev/null @@ -1,54 +0,0 @@ -New Rcpp versions 0.6.0 and 0.6.1 ---------------------------------- - -The Rcpp package provides C++ classes that greatly facilitate interfacing C -or C++ code in R packages using the .Call() interface provided by R. - -Rcpp provides matching C++ classes for a large number of basic R data -types. Hence, a package author can keep his data in normal R data structure -without having to worry about translation or transfer to C++. At the same -time, the data structures can be accessed as easily at the C++ level, and -used in the normal manner. - -The mapping of data types works in both directions. It is as straightforward -to pass data from R to C++, as it is it return data from C++ to R. The -following two sections list supported data types. - -Transfer from R to C++: -Standard R datatypes that are understood in C++ are - o named lists containing numeric (i.e. floating point), integer, - character, logical (i.e. boolean) or Date and Datetime (i.e. POSIXct at - the microsecond granularity) arguments; - o data frames containing numeric, integer, logical, character, - Date, Datetime or Factor columns; - o named vectors containing numeric or integer values, - o vectors and matrices of different values - o character strings - -Transfer from C++ to R: -Standard C++ datatypes can be returned to R in a named list, the most -general data type in R. Permissible components of the returns list -are the following C++ types: - o double (scalar as well as vectors and vectors of vectors), - o int (scalar as well as vectors and vectors of vectors), string, - o STL vector types and vector types of int and double - o STL vector of strings - o internal Rcpp types RcppDate, RcppDateVector, RcppDatetime, - RcppDatetimeVector, RcppStringVector, RcppVector of int or double, - RcppMatrix of int or double, RcppFrame - -Rcpp was initially written by Dominick Samperi as part of his contributions -to RQuantLib, and later released as a standalone package (under both the Rcpp -and RcppTemplate names). Its development had ceased in late 2006. - -As of November 2008, I have made new release with substantially expanded -documentation, simpler yet more comprehensive build structure leading to -easier use of Rcpp from other packages, and support for Windows, Linux and -Mac OS X (with special thanks to Simon for some extended cluebat waving). - -More information for Rcpp can be found at - o the package homepage at http://dirk.eddelbuettel.com/code/rcpp.html - o the R-forge repository at https://r-forge.r-project.org/projects/rcpp/ - o the CRAN page at http://cran.r-project.org/web/packages/Rcpp/index.html - -Regards, Dirk diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.7.0.txt b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.7.0.txt deleted file mode 100644 index 9b19b7e..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.7.0.txt +++ /dev/null @@ -1,74 +0,0 @@ -Rcpp version 0.7.0 went onto CRAN this weekend. The key new features are - - o inline support, taken from Oleg Sklyar's neat inline package and - adapted/extented to support Rcpp as well as external libraries - (see below for an example); this even works on Windows (provided you - have Rtools installed and configured); - - o addition of a new simple type RcppSexp for importing or exporting - simple types directly between R and C++ - - o addition of a number of new examples for both these features - - o code reorganisation: every class has in its own header and source file - - o last but not least relicensed from LGPL (>=2.1) to GPL (>= 2) - -My blog (http://dirk.eddelbuettel.com/blog/) has two recent posts with a bit -more details (and colour highlighting of the code below) but let's just look -at one example of using GNU GSL functions for illustrative purposes (as you -wouldn't need this to access random-number generators as R has its own). - -Consider this R code snippet: - - ## use Rcpp to pass down a parameter for the seed, and a vector size - gslrng <- ' - int seed = RcppSexp(s).asInt(); - int len = RcppSexp(n).asInt(); - - gsl_rng *r; - gsl_rng_env_setup(); - std::vector v(len); - - r = gsl_rng_alloc (gsl_rng_default); - - gsl_rng_set (r, (unsigned long) seed); - for (int i=0; i - v which is also converted on the fly. - - 5) The resulting vector is returned and simply printed at the R level. - - -More examples are in the source tarball and in the R-Forge SVN archive. - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.8.0.txt b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.8.0.txt deleted file mode 100644 index 467af3c..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.8.0.txt +++ /dev/null @@ -1,297 +0,0 @@ - -===== Summary ===== - -Version 0.8.0 of the Rcpp package was released to CRAN today. This release -marks another milestone in the ongoing redesign of the package, and -underlying C++ library. - - -===== Overview ===== - -Rcpp is an R package and C++ library that facilitates integration of C++ -code in R packages. - -The package features a set of C++ classes (Rcpp::IntegerVector, -Rcpp::Function, Rcpp::Environment, ...) that makes it easier to manipulate R -objects of matching types (integer vectors, functions, environments, etc -...). - -Rcpp takes advantage of C++ language features such as the explicit -constructor/destructor lifecycle of objects to manage garbage collection -automatically and transparently. We believe this is a major improvement over -PROTECT/UNPROTECT. When an Rcpp object is created, it protects the underlying -SEXP so that the garbage collector does not attempt to reclaim the -memory. This protection is withdrawn when the object goes out of -scope. Moreover, users generally do not need to manage memory directly (via -calls to new / delete or malloc / free) as this is done by the Rcpp classes -or the corresponding STL containers. - - -===== API ===== - -Rcpp provides two APIs: an older set of classes we refer to the classic API -(see below for the section 'Backwards Compatibility) as well as second and -newer set of classes. - -Classes of the new Rcpp API belong to the Rcpp namespace. Each class is -associated to a given SEXP type and exposes an interface that allows -manipulation of the object that may feel more natural than the usual use of -macros and functions provided by the R API. - ----------------------------------------------------------- -SEXP type | Rcpp class ----------------------------------------------------------- -INTSXP | Rcpp::IntegerVector -REALSXP | Rcpp::NumericVector -RAWSXP | Rcpp::RawVector -LGLSXP | Rcpp::LogicalVector -CPLXSXP | Rcpp::ComplexVector -STRSXP | Rcpp::CharacterVector -VECSXP | Rcpp::List -EXPRSXP | Rcpp::ExpressionVector ----------------------------------------------------------- -ENVSXP | Rcpp::Environment -SYMSXP | Rcpp::Symbol ----------------------------------------------------------- -CLOSXP | -BUILTINSXP | Rcpp::Function -SPECIALSXP | ----------------------------------------------------------- -LANGSXP | Rcpp::Language -LISTSXP | Rcpp::Pairlist ----------------------------------------------------------- -S4SXP | Rcpp::S4 ----------------------------------------------------------- -PROMSXP | Rcpp::Promise -WEAKREFSXP | Rcpp::WeakReference -EXTPTRSXP | template Rcpp::XPtr ----------------------------------------------------------- - -Some SEXP types do not have dedicated Rcpp classes : NILSXP, DOTSXP, -ANYSXP, BCODESXP and CHARSXP. - -Still missing are a few convenience classes such as Rcpp::Date or -Rcpp::Datetime which would map useful and frequently used R data types, but -which do not have an underlying SEXP type. - - -===== Data Interchange ===== - -Data interchange between R and C++ is managed by extensible and powerful yet -simple mechanisms. - -Conversion of a C++ object is managed by the template function Rcpp::wrap. -This function currently manages : - - primitive types : int, double, bool, float, Rbyte, ... - - std::string, const char* - - STL containers such as std::vector and STL maps such as - std::map< std::string, T> provided that the template type T is wrappable -- any class that can be implicitely converted to SEXP, through operator SEXP() - -Conversion of an R object to a C++ object is managed by the Rcpp::as -template which can handle: - - primitive types - - std::string, const char* - - STL containers such as std::vector - -Rcpp::wrap and Rcpp::as are often used implicitely. For example, when -assigning objects to an environment: - - // grab the global environment - Rcpp::Environment global = Rcpp::Environment::global_env() ; - std::deque z( 3 ); z[0] = false; z[1] = true; z[3] = false ; - - global["x"] = 2 ; // implicit call of wrap - global["y"] = "foo"; // implicit call of wrap - global["z"] = z ; // impl. call of wrap> - - int x = global["x"] ; // implicit call of as - std::string y = global["y"] // implicit call of as - std::vector z1 = global["z"] ; // impl. call of as> - -Rcpp contains several examples that illustrate wrap and as. The mechanism was -designed to be extensible. We have developped separate packages to illustrate -how to extend Rcpp conversion mechanisms to third party types. - - RcppArmadillo : conversion of types from the Armadillo C++ library. - - RcppGSL : conversion of types from the GNU Scientific Library. - -Rcpp is also used for data interchange by the RInside package which provides -and easy way of embedding an R instance inside of C++ programs. - - -===== inline use ===== - -Rcpp depends on the inline package by Oleg Sklyar et al. Rcpp then uses the -'cfunction' provided by inline (with argument Rcpp=TRUE) to compile, link and -load C++ function from the R session. - -As of version 0.8.0 of Rcpp, we also define an R function cppfunction that -acts as a facade function to the inline::cfuntion, with specialization for -C++ use. - -This allows quick prototyping of compiled code. All our unit tests are based -on cppfunction and can serve as examples of how to use the mechanism. For example -this function (from the runit.GenericVector.R unit test file) defines from -R a C++ (simplified) version of lapply: - - ## create a compiled function cpp_lapply using cppfunction - cpp_lapply <- cppfunction(signature(x = "list", g = "function" ), - 'Function fun(g) ; - List input(x) ; - List output( input.size() ) ; - std::transform( input.begin(), input.end(), output.begin(), fun ) ; - output.names() = input.names() ; - return output ; - ') - ## call cpp_lapply on the iris data with the R function summary - cpp_lapply( iris, summary ) - - -===== Using Rcpp in other packages ===== - -Rcpp is designed so that its classes are used from other packages. Using Rcpp -requires : - - using the header files provided by Rcpp. This is typically done by adding this - line in the package DESRIPTION file: - - LinkingTo: Rcpp - - and add the following line in the package code: - - #include - -- linking against the Rcpp dynamic or static library, which is achieved by - adding this line to the src/Makevars of the package: - - PKG_LIBS = $(shell ${R_HOME}/bin/Rscript -e "Rcpp:::LdFlags()" ) - - and this line to the src/Makevars.win file: - - PKG_LIBS = $(shell "${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe" -e "Rcpp:::LdFlags()") - -Rcpp contains a function Rcpp.package.skeleton, modelled after -package.skeleton from the utils package in base r, that creates a skeleton of -a package using Rcpp, including example code. - - -===== C++ exceptions ===== - -C++ exceptions are R contexts are both based on non local jumps (at least -on the implementation of exceptions in gcc), so care must be ensure -that one system does not void assumptions of the other. It is therefore -very strongly recommended that each function using C++ catches -C++ exceptions. Rcpp offers the function forward_exception_to_r -to facilitate forwarding the exception to the "R side" as an R condition. -For example : - - SEXP foo( ) { - try { - // user code here - } catch( std::exception& __ex__){ - forward_exception_to_r( __ex__ ) ; - } - // return something here - } - -Alternatively, functions can enclose the user code with the macros BEGIN_RCPP -and END_RCPP, which provides for a more compact way of programming. The -function above could be written as follows using the macros: - - SEXP foo( ) { - BEGIN_RCPP - // user code here - END_RCPP - // return something here - } - -The use of BEGIN_RCPP and END_RCPP is recommended to anticipate future changes -of Rcpp. We might for example decide to install dedicated handlers for specific -exceptions later. - - -===== Experimental code generation macros ===== - -Rcpp contains several macros that can generate repetitive 'boiler plate' code: - RCPP_FUNCTION_0, ..., RCPP_FUNCTION_65 - RCPP_FUNCTION_VOID_0, ..., RCPP_FUNCTION_VOID_65 - RCPP_XP_METHOD_0, ..., RCPP_XP_METHOD_65 - RCPP_XP_METHOD_CAST_0, ..., RCPP_XP_METHOD_CAST_65 - RCPP_XP_METHOD_VOID_0, ..., RCPP_XP_METHOD_VOID_65 - -For example: - - RCPP_FUNCTION_2( int, foobar, int x, int y){ - return x + y ; - } - -This will create a .Call compatible function "foobar" that calls a -c++ function for which we provide the argument list (int x, int y) -and the return type (int). The macro also encloses the call -in BEGIN_RCPP/END_RCPP so that exceptions are properly forwarded to R. - -Examples of the other macros are given in the NEWS file. - -This feature is still experimental, but is being used in packages -highlight and RProtoBuf - - -===== Quality Assurance ===== - -Rcpp uses the RUnit package by Matthias Burger et al and the aforementioned -inline package by Oleg Sklyar et al to provide unit testing. Rcpp currently -has over 500 unit tests (called from more than 230 unit test functions) with -very good coverage of the critical parts of the package and library. - -Source code for unit test functions are stored in the unitTests directory -of the installed package and the results are collected in the "Rcpp-unitTests" -vignette. - -The unit tests can be both during the standard R package build and testing -process, and also when the package is installed. The latter use is helpful -to ensure that no system components have changed in a way that affect the -Rcpp package since it has been installed. To run the tests, execute - - Rcpp:::test() - -where an output directory can be provided as an optional first argument. - - -===== Backwards Compatibility ===== - -We believe the new API is now more complete and useful than the previous set -of classes, which we refer to as the "classic Rcpp API". We would therefore -recommend to package authors using 'classic' Rcpp to move to the new API. -However, the classic API is still maintained and will continue to be -maintained to ensure backwards compatibility for code that uses it. - -Packages uses the 'Classic API' can use features of the new API selectively -and in incremental steps. This provides for a non-disruptive upgrade path. - - -===== Documentation ===== - -The package contains a vignette which provides a short and succinct -introduction to the Rcpp package along with several motivating examples. -Also provided is a vignette containing the regression test summary from -the time the package was built. - - -===== Links ===== - -Rcpp main page: http://dirk.eddelbuettel.com/code/rcpp.html -R-forge project page: http://r-forge.r-project.org/projects/rcpp/ -Dirk's blog section about Rcpp: http://dirk.eddelbuettel.com/blog/code/rcpp/ -Romain's blog section about Rcpp: http://romainfrancois.blog.free.fr/index.php?category/R-package/Rcpp - - -===== Support ===== - -Questions about Rcpp should be directed to the Rcpp-devel mailing list -https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel - - - - -- Dirk Eddelbuettel and Romain Francois - Chicago, IL, USA, and Montpellier, France - May 2010 - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.9.0.txt b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.9.0.txt deleted file mode 100644 index 4b99fa8..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/announce/ANNOUNCE-0.9.0.txt +++ /dev/null @@ -1,196 +0,0 @@ - -===== Summary ===== - -Version 0.9.0 of the Rcpp package is now on CRAN and its mirrors. This -release marks another step in the development of the package, and a few key -points are highlighted below. More details are in the NEWS and ChangeLog -files included in the package. - - -===== Overview ===== - -Rcpp is an R package and associated C++ library that facilitates integration -of C++ code in R packages. - -The package features a complete set of C++ classes (Rcpp::IntegerVector, -Rcpp:NumericVector, Rcpp::Function, Rcpp::Environment, ...) that makes it -easier to manipulate R objects of matching types (integer vectors, functions, -environments, etc ...). - -Rcpp takes advantage of C++ language features such as the explicit -constructor / destructor lifecycle of objects to manage garbage collection -automatically and transparently. We believe this is a major improvement over -use of PROTECT/UNPROTECT. When an Rcpp object is created, it protects the -underlying SEXP so that the garbage collector does not attempt to reclaim the -memory. This protection is withdrawn when the object goes out of -scope. Moreover, users generally do not need to manage memory directly (via -calls to new / delete or malloc / free) as this is done by the Rcpp classes -or the corresponding STL containers. - -A few key points about Rcpp: - - - a rich API covering all core R data types including vectors, matrices, - functions, environments, ... (with the exeception of factors - which are less useful in C++) - - - seamless (bi-directional) data interchange between R and C++ - - - possibility of inline use permitting definition, compilation, linking and - loading of C++ functions directly from R - - - extensive documentation now covering eight vignettes - - - exception handling and error propagation back to R - - - extensive test suite using RUnit covering over 700 tests - - - extension packages RcppArmadillo and RcppGSL provide easy-to-use - integration with the Armadillo (linear algebra) and GNU GSL librasries - - - increasing adoption among R users and package developers with now - twenty packages from CRAN or BioConductor depending on Rcpp - - - support for the legacy 'classic' Rcpp is now provided by the RcppClassic - package which is being released concurrently with Rcpp 0.9.0 - -Several key features were added during the 0.8.* cycles and are described below. - - -===== Rcpp sugar ===== - -Rcpp now provides syntactic sugar: vectorised expressions at the C++ level -which are motivated by the corresponding R expressions. This covers -operators (binary arithmetic, binary logical, unary), functions (producing -single logical results, mathematical functions and d/p/q/r statistical -functions). Examples comprises anything from ifelse() to pmin()/pmax() or - -A really simply example is a function - - SEXP foo( SEXP xx, SEXP yy){ - NumericVector x(xx), y(yy) ; - return ifelse( x < y, x*x, -(y*y) ) ; - } - -which deploys the sugar 'ifelse' function modeled after the corresponding R -function. Another simple example is - - double square( double x){ - return x*x ; - } - - SEXP foo( SEXP xx ){ - NumericVector x(xx) ; - return sapply( x, square ) ; - } - -where use the sugar function 'sapply' to sweep a simple C++ function which -operates elementwise across the supplied vector. - -The Rcpp-sugar vignette describes sugar in more detail. - - -===== Rcpp modules ===== - -Rcpp modules are inspired by Boost.Python and make exposing C++ functions or -classes to R even easier. A first illustration is provided by this simple -C++ code snippet - - const char* hello( const std::string& who ){ - std::string result( "hello " ) ; - result += who ; - return result.c_str() ; - } - - RCPP_MODULE(yada){ - using namespace Rcpp ; - function( "hello", &hello ) ; - } - -which (after compiling and loading) we can access in R as - - yada <- Module( "yada" ) - yada$hello( "world" ) - -In a similar way, C++ classes can be exposed very easily. - -Rcpp modules are also described in more detail in their own vignette. - - -===== Reference Classes ===== - -R release 2.12.0 introduced Reference Classes. These are formal S4 classes -with the corresponding dispatch method, but passed by reference and easy to -use. Reference Classes can also be exposed to R by using Rcpp modules. - - -===== Extension packackages ===== - -The RcppArmadillo package permits use of the advanced C++ library 'Armadillo, -a C++ linear algebra library aiming towards a good balance between speed and -ease of use, providing integer, floating point and complex matrices and -vectors with lapack / blas support via R. Armadillo uses templates for a -delayed evaluation approach is employed (during compile time) to combine -several operations into one and reduce (or eliminate) the need for -temporaries. Armadillo is useful if C++ has been decided as the language of -choice, rather than another language like Matlab ® or Octave, and aims to be -as expressive as the former. Via Rcpp and RcppArmadillo, R users now have -easy access to this functionality. Examples are provided in the RcppArmadillo -package. - -The RcppGSL package permits easy use of the GNU Scientific Library (GSL), a -collection of numerical routines for scientifc computing. It is particularly -useful for C and C++ programs as it provides a standard C interface to a wide -range of mathematical routines such as special functions, permutations, -combinations, fast fourier transforms, eigensystems, random numbers, -quadrature, random distributions, quasi-random sequences, Monte Carlo -integration, N-tuples, differential equations, simulated annealing, numerical -differentiation, interpolation, series acceleration, Chebyshev -approximations, root-finding, discrete Hankel transforms physical constants, -basis splines and wavelets. There are over 1000 functions in total with an -extensive test suite. The RcppGSL package provides an easy-to-use interface -between GSL data structures and R using concepts from Rcpp. The RcppGSL -package also contains a vignette with more documentation. - - -===== Legacy 'classic' API ===== - -Packages still using code interfacing the initial 'classic' Rcpp API are -encouraged to migrate to the new API. Should a code transition not be -possible, backwards compatibility is provided by the RcppClassic package -released alongside Rcpp 0.9.0. By including RcppClassic.h and building -against the RcppClassic package and library, vintage code can remain -operational using the classic API. The short vignette in the RcppClassic -package has more details. - - -===== Documentation ===== - -The package contains a total of eight vignettes the first of which provides a -short and succinct introduction to the Rcpp package along with several -motivating examples. - - -===== Links ===== - -Rcpp main page: - http://dirk.eddelbuettel.com/code/rcpp.html -R-forge project page: - http://r-forge.r-project.org/projects/rcpp/ -Dirk's blog section about - Rcpp: http://dirk.eddelbuettel.com/blog/code/rcpp/ -Romain's blog section about Rcpp: - http://romainfrancois.blog.free.fr/index.php?category/R-package/Rcpp - - -===== Support ===== - -Questions about Rcpp should be directed to the Rcpp-devel mailing list - https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel - - - - -- Dirk Eddelbuettel, Romain Francois, Doug Bates and John Chambers - December 2010 - - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/bib/Rcpp.bib b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/bib/Rcpp.bib deleted file mode 100644 index c3c5f26..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/bib/Rcpp.bib +++ /dev/null @@ -1,666 +0,0 @@ -@String{CRAN = "http://CRAN.R-Project.org/" } -@String{manuals = CRAN # "doc/manuals/" } -@String{RCoreTeam = "{R Core Team}" } -@String{RFoundation = "R Foundation for Statistical Computing" } -@String{R-Forge = "http://R-Forge.R-Project.org/" } - -@Misc{Cpp11, - author = "ISO/IEC", - organization = "{International Organization for Standardization}", - title = "\proglang{C++} 2011 Standard Document 14882:2011", - howpublished = {ISO/IEC Standard Group for Information Technology / Programming Languages / C++}, - year = 2011, - url = "http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=50372", - urlansi = "http://webstore.ansi.org/RecordDetail.aspx?sku=ISO/IEC%2014882:2011" -} - -@manual{Abrahams+Grosse-Kunstleve:2003:Boost.Python, - author = { David Abrahams and Ralf W. Grosse-Kunstleve }, - organization = "Boost Consulting", - title = "Building Hybrid Systems with Boost.Python", - year = 2003, - url = "http://www.boostpro.com/writing/bpl.pdf" -} - -@Book{Abrahams+Gurtovoy:2004:TemplateMetaprogramming, - author = {David Abrahams and Aleksey Gurtovoy}, - title = {{C++} {T}emplate {M}etaprogramming: Concepts, Tools - and Techniques from {B}oost and Beyond}, - publisher = {Addison-Wesley}, - year = 2004, - address = {Boston} -} - -@Manual{Armstrong:2009:RAbstraction, - title = {{RAbstraction}: {C++} abstraction for {R} objects}, - author = {Whit Armstrong}, - year = 2009, - note = {Code repository last updated 2009-07-22.}, - url = {http://github.com/armstrtw/rabstraction} -} - -@Manual{Armstrong:2009:RObjects, - title = {{RObjects}: {C++} wrapper for R objects (a better - implementation of {RAbstraction}}, - author = {Whit Armstrong}, - year = 2009, - note = {Code repository last updated 2009-11-28.}, - url = {http://github.com/armstrtw/RObjects} -} - -@InProceedings{Bates+DebRoy:2001:C++Classes, - author = {Douglas M. Bates and Saikat DebRoy}, - title = {{C++} Classes for {R} Objects}, - booktitle = {Proceedings of the 2nd International Workshop on Distributed - Statistical Computing, March 15--17, 2001, Technische - Universit\"at Wien, Vienna, Austria}, - editor = {Kurt Hornik and Friedrich Leisch}, - year = {2001}, - url = {http://www.ci.tuwien.ac.at/Conferences/DSC-2001/Proceedings/}, - note = {ISSN 1609-395X} -} - - -@Misc{Brokken:2011:Cpp, - author = {Frank B. Brokken}, - title = {C++ Annotations}, - howpublished = {Electronic book, University of Groningen}, - year = 2011, - url = {http://www.icce.rug.nl/documents/cplusplus/} -} - -@Book{Chambers:2008:SoDA, - author = {John M. Chambers}, - title = {Software for Data Analysis: Programming with {R}}, - publisher = {Springer-Verlag}, - year = 2008, - series = {Statistics and Computing}, - address = {Heidelberg}, - note = {{ISBN} 978-0-387-75935-7} -} - -@Book{Chambers:1998:PwD, - author = {John M. Chambers}, - title = {Programming with Data: {A} Guide to the {S} Language}, - publisher = {Springer-Verlag}, - year = 1998, - address = {Heidelberg}, - note = {{ISBN} 978-0387985039} -} - -@Manual{CRAN:RInside, - title = {RInside: C++ classes to embed R in C++ applications}, - author = {Dirk Eddelbuettel and Romain Fran\c{c}ois}, - year = 2015, - note = {R package version 0.2.13}, - url = CRAN # "package=RInside" -} - -@Manual{CRAN:RProtoBuf, - title = {RProtoBuf: R Interface to the Protocol Buffers API}, - author = {Romain Fran\c{c}ois and Dirk Eddelbuettel and Murray Stokely and Jeroen Ooms}, - year = 2016, - note = {R package version 0.4.7}, - url = CRAN # "package=RProtoBuf" -} - -@Manual{CRAN:RQuantLib, - title = {RQuantLib: {R} interface to the {QuantLib} library}, - author = {Dirk Eddelbuettel and Khanh Nguyen}, - year = 2016, - note = {R package version 0.4.3}, - url = CRAN # "package=RQuantLib" -} - -@Manual{CRAN:rbenchmark, - title = {\pkg{rbenchmark}: Benchmarking routine for \proglang{R}}, - author = {Wacek Kusnierczyk}, - year = 2012, - note = {R package version 1.0.0}, - url = CRAN # "package=rbenchmark" -} - -@Article{JSS:Rcpp, - title = {{Rcpp}: Seamless {R} and {C++} Integration}, - author = {Dirk Eddelbuettel and Romain Fran\c{c}ois}, - journal = {Journal of Statistical Software}, - year = 2011, - volume = 40, - number = 8, - pages = {1--18}, - url = {http://www.jstatsoft.org/v40/i08/}, -} - -@Manual{CRAN:Rcpp, - title = {{Rcpp}: Seamless {R} and {C++} Integration}, - author = {Dirk Eddelbuettel and Romain Fran\c{c}ois and JJ - Allaire and Kevin Ushey and Qiang Kou and - Nathan Russel and John Chambers and Douglas Bates}, - year = 2017, - note = {R package version 0.12.12}, - url = CRAN # "package=Rcpp" -} - -@Manual{CRAN:Rcpp:Attributes, - crossref = {CRAN:Rcpp}, - author = {J. J. Allaire and Dirk Eddelbuettel and Romain Fran\c{c}ois}, - title = {{Rcpp} Attributes}, - year = 2015, - note = {Vignette included in R package Rcpp}, - url = CRAN # "package=Rcpp" -} - -@Manual{CRAN:Rcpp:Modules, - crossref = {CRAN:Rcpp}, - author = {Dirk Eddelbuettel and Romain Fran\c{c}ois}, - title = {Exposing {C++} functions and classes with {Rcpp} modules}, - year = 2015, - note = {Vignette included in R package Rcpp}, - url = CRAN # "package=Rcpp" -} - -@Manual{CRAN:Rcpp:Sugar, - crossref = {CRAN:Rcpp}, - author = {Dirk Eddelbuettel and Romain Fran\c{c}ois}, - title = {{Rcpp} syntactic sugar}, - year = 2015, - note = {Vignette included in R package Rcpp}, - url = CRAN # "package=Rcpp" -} - -@Manual{CRAN:RcppArmadillo, - title = {RcppArmadillo: Rcpp integration for Armadillo - templated linear algebra library}, - author = {Dirk Eddelbuettel and Romain Fran\c{c}ois and - Douglas Bates}, - year = 2016, - note = {R package version 0.7.400.2.0}, - url = CRAN # "package=RcppArmadillo" -} - -@Manual{CRAN:RcppClassic, - title = {RcppClassic: Deprecated 'classic' Rcpp API}, - author = {Dirk Eddelbuettel and Romain Fran\c{c}ois}, - year = 2015, - note = {R package version 0.9.6}, - url = CRAN # "package=RcppClassic" -} - -@Manual{CRAN:RcppDE, - title = {RcppDE: Global optimization by differential evolution in C++}, - author = {Dirk Eddelbuettel}, - year = 2016, - note = {R package version 0.1.5}, - url = CRAN # "package=RcppDE" -} - -@Manual{CRAN:RcppEigen, - title = {RcppEigen: Rcpp integration for the Eigen templated linear - algebra library}, - author = {Douglas Bates and Romain Fran\c{c}ois and Dirk Eddelbuettel}, - year = 2016, - note = {{R} package version 0.3.2.9.0}, - url = CRAN # "package=RcppEigen" -} - -@Article{JSS:RcppEigen, - title = {Fast and Elegant Numerical Linear Algebra Using the - {RcppEigen} Package}, - author = {Douglas Bates and Dirk Eddelbuettel}, - journal = {Journal of Statistical Software}, - year = {2013}, - volume = {52}, - number = {5}, - pages = {1--24}, - url = {http://www.jstatsoft.org/v52/i05/}, -} - -@Article{JSS:RProtoBuf, - title = {{RProtoBuf}: Efficient Cross-Language Data Serialization in - {R}}, - author = {Dirk Eddelbuettel and Murray Stokely and Jeroen Ooms}, - journal = {Journal of Statistical Software}, - year = {2016}, - volume = {71}, - number = {2}, - pages = {1--24}, - doi = {10.18637/jss.v071.i02}, -} - -@Manual{CRAN:RcppExamples, - title = {RcppExamples: Examples using {Rcpp} to interface {R} - and {C++}}, - author = {Dirk Eddelbuettel and Romain Fran\c{c}ois}, - year = 2016, - note = {R package version 0.1.8}, - url = CRAN # "package=RcppExamples" -} - -@Manual{CRAN:RcppGSL, - title = {RcppGSL: Rcpp integration for GNU GSL vectors and matrices}, - author = {Dirk Eddelbuettel and Romain Fran\c{c}ois}, - year = 2016, - note = {R package version 0.3.1}, - url = CRAN # "package=RcppGSL" -} - -@Manual{CRAN:RcppZiggurat, - title = {RcppZiggurat: Rcpp Integration of Different Ziggurat Normal RNG Implementations}, - author = {Dirk Eddelbuettel}, - year = 2015, - note = {R package version 0.1.3}, - url = CRAN # "package=RcppZiggurat" -} - -@Manual{CRAN:Rserve, - title = {Rserve: Binary R server}, - author = {Simon Urbanek}, - year = 2013, - note = {R package version 1.7-3}, - url = CRAN # "package=Rserve" -} - -@Manual{CRAN:cxxPack, - title = {cxxpack: {R/C++} Tools for Literate Statistical - Practice}, - author = {Dominick Samperi}, - year = 2010, - note = {R package version 7.0.6}, - url = CRAN # "package=cxxPack" -} - -@Manual{CRAN:highlight, - title = {highlight: Syntax highlighter}, - author = {Romain Fran\c{c}ois}, - year = 2015, - note = {R package with version 0.4.7}, - url = CRAN # "package=highlight" -} - -@Manual{CRAN:inline, - title = {inline: Inline C, C++, Fortran function calls from - R}, - author = {Oleg Sklyar and Duncan Murdoch and Mike Smith and - Dirk Eddelbuettel and Romain Fran\c{c}ois}, - year = 2015, - note = {R package version 0.3.14}, - url = CRAN # "package=inline" -} - -@Manual{CRAN:Matrix, - title = {\pkg{Matrix}: Sparse and Dense Matrix Classes and Methods}, - author = {Douglas Bates and Martin Maechler}, - year = 2016, - note = {R package version 1.2-7.1}, - url = CRAN # "package=Matrix" -} - -@Manual{CRAN:minqa, - title = {minqa: Derivative-free optimization algorithms by - quadratic approximation}, - author = {Douglas Bates and Katharine M. Mullen and John - C. Nash and Ravi Varadhan}, - year = 2014, - note = {R package version 1.2.4}, - url = CRAN # "package=minqa" -} - -@Manual{CRAN:roxygen2, - title = {roxygen2: In-source documentation for R}, - author = {Hadley Wickham and Peter Danenberg and Manuel Eugster}, - year = 2015, - note = {R package version 5.0.1}, - url = CRAN # "package=roxygen2" -} - -@Book{Eddelbuettel:2013:Rcpp, - author = {Dirk Eddelbuettel}, - title = {Seamless R and C++ Integration with Rcpp}, - publisher = {Springer}, - series = {Use R!}, - year = 2013, - address = {New York}, - isbn = {978-1-4614-6867-7} -} - -@Article{Eddelbuettel+Sanderson:2013:RcppArmadillo, - title = {{RcppArmadillo}: Accelerating {R} with High-Performance {C++} Linear Algebra}, - author = {Dirk Eddelbuettel and Conrad Sanderson}, - journal = {Computational Statistics and Data Analysis}, - year = 2014, - volume = 71, - month = {March}, - pages = {1054--1063}, - doi = {10.1016/j.csda.2013.02.005}, - url = {http://dx.doi.org/10.1016/j.csda.2013.02.005} -} - -@Article{Eddelbuettel+Sanderson:2014:RcppArmadillo, - title = {{RcppArmadillo}: Accelerating {R} with High-Performance {C++} Linear Algebra}, - author = {Dirk Eddelbuettel and Conrad Sanderson}, - journal = {Computational Statistics and Data Analysis}, - year = 2014, - volume = 71, - month = {March}, - pages = {1054--1063}, - doi = {10.1016/j.csda.2013.02.005}, - url = {http://dx.doi.org/10.1016/j.csda.2013.02.005} -} - -; see http://eigen.tuxfamily.org/index.php?title=BibTeX -; replaced 'howpublished' with 'url' and updated year to 2011, and again to 2012 -@MISC{Eigen:Web, - author = {Ga\"{e}l Guennebaud and Beno\^{i}t Jacob and others}, - title = {Eigen v3}, - year = 2012, - url = {http://eigen.tuxfamily.org}, -} - -@Book{Gentleman:2009:RProgramming, - author = {Robert Gentleman}, - title = {R Programming for Bioinformatics}, - publisher = {Chapman \& Hall/CRC}, - year = 2009, - series = {Computer Science and Data Analysis}, - address = {Boca Raton, FL} -} - -@Article{Gropp+Lusk+Doss+Skjellum:1996:MPI, - author = {William Gropp and Ewing Lusk and Nathan Doss and Anthony Skjellum}, - title = {A high-performance, portable implementation of the {MPI} message passing interface standard}, - journal = {Parallel Computing}, - year = 1996, - url = {http://dx.doi.org/10.1016/0167-8191(96)00024-5}, - volume = 22, - number = 6, - pages = {789--828} -} - -@Book{Gropp+Lusk+Skjellum:1999:MPI, - author = {William Gropp and Ewing Lusk and Anthony Skjellum}, - title = {Using {MPI}: Portable Parallel Programming with the Message Passing Interface}, - publisher = {MIT Press}, - year = 1999, - series = {Scientific and Engineering Computation Series}, - edition = {2nd}, - month = {November}, - note = {{ISBN} 978-0-262-57132-6}} - -@Manual{GSL, - title = {{GNU} {S}cientific {L}ibrary {R}eference {M}anual}, - author = {Mark Galassi and Jim Davies and James Theiler and Brian Gough and Gerard Jungman and Patrick Alken and Michael Booth and Fabrice Rossi}, - year = {2010}, - edition = {3rd}, - note = {Version 1.14. {ISBN} 0954612078}, - url = {http://www.gnu.org/software/gsl} -} - -@Unpublished{Java+Gaile+Manly:2007:RCpp, - author = {James J. Java and Daniel P. Gaile and Kenneth - E. Manly}, - title = {{R/Cpp}: Interface Classes to Simplify Using {R} - Objects in {C++} Extensions}, - note = {Unpublished manuscript, University at Buffalo}, - url = - {http://sphhp.buffalo.edu/biostat/research/techreports/UB_Biostatistics_TR0702.pdf}, - month = {July}, - year = 2007 -} - -@InProceedings{Leisch:2008:Tutorial, - author = {Friedrich Leisch}, - title = {Tutorial on {C}reating \proglang{R} {P}ackages}, - booktitle = {COMPSTAT 2008 -- Proceedings in Computational - Statistics}, - year = 2008, - editor = {Paula Brito}, - address = {Heidelberg}, - publisher = {Physica Verlag}, - url = CRAN # "doc/contrib/Leisch-CreatingPackages.pdf" -} - -@Manual{Liang:2008:rcppbind, - title = {rcppbind: {A} template library for R/C++ developers}, - author = {Gang Liang}, - year = 2008, - note = {R package version 1.0}, - url = R-Forge # "projects/rcppbind" -} - -@Book{Lippman+Lajoie+Moo:2005:Cpp_Primer, - author = {Stanley B. Lippman and Jos\'{e}e Lajoie and Barbara E. Moo}, - title = {The C++ Primer}, - publisher = {Addison-Wesley}, - address = {Boston}, - year = 2005, - edition = {4th} -} - -@Book{Matloff:2011:ArtOfR, - author = {Norman Matloff}, - title = {The Art of R Programming: A Tour of Statistical Software Design}, - publisher = {No Starch Press}, - address = {San Francisco, CA}, - year = 2011 -} - -@book{Meyers:1995:MoreEffectiveC++, - author = {Scott Meyers}, - title = {More Effective C++: 35 New Ways to Improve Your - Programs and Designs}, - year = 1995, - note = {{ISBN} 020163371X}, - publisher = {Addison-Wesley}, - address = {Boston} -} - -@book{Meyers:2001:EffectiveSTL, - author = {Scott Meyers}, - title = {Effective STL: 50 specific ways to improve your use - of the standard template library}, - year = 2001, - note = {{ISBN} 0-201-74962-9}, - publisher = {Addison-Wesley}, - address = {Essex} -} - -@book{Meyers:2005:EffectiveC++, - author = {Scott Meyers}, - title = {Effective C++: 55 Specific Ways to Improve Your - Programs and Designs}, - year = 2005, - note = {{ISBN} 978-0321334879}, - publisher = {Addison-Wesley}, - address = {Boston}, - edition = {3rd}, -} - -@Book{Plauger+Et+Al:2000:STL, - author = {P.J. Plauger and Alexander Stepanov and Meng Lee and - David R. Musser}, - title = {The {C++} Standard Template Library}, - publisher = {Prentice Hall PTR}, - year = 2000, - note = {{ISBN} 978-0134376332}, -} - -@manual{R:Administration, - author = RCoreTeam, - organization = RFoundation, - address = {Vienna, Austria}, - year = 2015, - title = "R Installation and Administration", - annote = {{ISBN} 3-900051-09-7}, - url = manuals # "R-admin.html" -} - -@manual{R:Extensions, - author = RCoreTeam, - organization = RFoundation, - address = {Vienna, Austria}, - year = 2015, - title = "Writing R extensions", - annote = {{ISBN} 3-900051-11-9}, - url = manuals # "R-exts.html" -} - -@manual{R:Internals, - author = RCoreTeam, - organization = RFoundation, - address = {Vienna, Austria}, - year = 2015, - title = "R internals", - annote = {{ISBN} 3-900051-14-3}, - url = manuals # "R-ints.html" -} - -@manual{R:Main, - title = {R: A Language and Environment for Statistical - Computing}, - author = RCoreTeam, - organization = RFoundation, - address = {Vienna, Austria}, - year = 2015, - url = {http://www.R-project.org/}, -} - -@manual{R:Language, - author = RCoreTeam, - organization = RFoundation, - address = {Vienna, Austria}, - year = 2015, - title = "R language", - annote = {{ISBN} 3-900051-13-5}, - url = manuals # "R-lang.html" -} - -@Book{Venables+Ripley:2000:SProgramming, - author = {Willian N. Venables and Brian D. Ripley}, - title = {S Programming}, - publisher = {Springer-Verlag}, - year = 2000, - series = {Statistics and Computing}, - address = {New York} -} - -@InProceedings{Runnalls:2009:CXXR, - author = {Andrew Runnalls}, - title = {Aspects of {CXXR} internals}, - booktitle = {Directions in Statistical Computing}, - address = {University of Copenhagen, Denmark}, - year = 2009 -} - -@Manual{Samperi:2009:RcppTemplate, - title = {RcppTemplate: Rcpp {R/C++} Object Mapping Library - and Package Template}, - author = {Dominick Samperi}, - year = 2009, - note = {(Archived) R package version 6.1}, - url = CRAN # "/src/contrib/Archive/RcppTemplate" -} - -@TechReport{Sanderson:2010:Armadillo, - author = {Conrad Sanderson}, - title = {{Armadillo}: {An} open source {C++} Algebra Library - for Fast Prototyping and Computationally Intensive - Experiments }, - institution = {{NICTA}}, - year = 2010, - url = "http://arma.sf.net" -} - -@Book{Stroustrup:1997:Cpp, - author = {Bjarne Stroustrup}, - title = {The C++ Programming Language}, - publisher = {Addison-Wesley}, - address = {Boston}, - year = 1997, - edition = {3rd} -} - -@Book{Stroustrup:2013:Cpp, - author = {Bjarne Stroustrup}, - title = {The C++ Programming Language}, - publisher = {Addison-Wesley}, - address = {Boston}, - year = 2013, - pages = 1368, - edition = {4th} -} - -@Article{TempleLang:2009:ModestProposal, - author = {Duncan {Temple Lang}}, - title = {A modest proposal: an approach to making the - internal {R} system extensible}, - journal = {Computational Statistics}, - year = 2009, - volume = 24, - number = 2, - pages = {271-281}, - month = {May} -} - -@Article{TempleLang:2009:RGCCTranslationUnit, - author = {Duncan {Temple Lang}}, - title = {Working with meta-data from {C/C++} code in {R}: the - {RGCCTranslationUnit} package}, - journal = {Computational Statistics}, - year = 2009, - volume = 24, - number = 2, - pages = {283-293}, - month = {May} -} - -@InProceedings{Maurer+Wong:2008:AttributesInC++, - author = {Jens Maurer and Michael Wong}, - title = {Towards support for attributes in {C++} (Revision - 6)}, - booktitle = {JTC1/SC22/WG21 - The C++ Standards Committee}, - year = {2008}, - url = - {http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2761.pdf}, - note = {{N2761=08-0271}} -} - -@InProceedings{Urbanek:2003:Rserve, - author = {Simon Urbanek}, - title = {{Rserve}: A Fast Way to Provide {R} Functionality to - Applications}, - booktitle = {Proceedings of the 3rd International Workshop on Distributed - Statistical Computing, Vienna, Austria}, - editor = {Kurt Hornik and Friedrich Leisch and Achim Zeileis}, - year = {2003}, - url = {http://www.ci.tuwien.ac.at/Conferences/DSC-2003/Proceedings/}, - note = {{ISSN 1609-395X}} -} - -@Book{Vandevoorde+Josuttis:2003:Templates, - author = {David Vandevoorde and Nicolai M. Josuttis}, - title = {{C++} {T}emplates: The Complete Guide}, - publisher = {Addison-Wesley}, - year = 2003, - address = {Boston} -} - -@inproceedings{Veldhuizen:1998:Blitz, - author = {Todd L. Veldhuizen}, - title = {Arrays in {Blitz++}}, - booktitle = {ISCOPE '98: Proceedings of the Second International - Symposium on Computing in Object-Oriented Parallel - Environments}, - note = {{ISBN} 3-540-65387-2}, - year = 1998, - pages = {223--230}, - publisher = {Springer-Verlag}, - address = {London}, -} - -@misc{KDE-TechBase:2012, - author = {KDE-TechBase}, - title = {Binary Compatibility Issues With {C++}}, - url = "http://techbase.kde.org/Policies/Binary_Compatibility_Issues_With_C++", - year = 2012, - note = "[Online; accessed 24-November-2012]" -} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/discovery/cxx0x.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/discovery/cxx0x.R deleted file mode 100644 index 5cc3da4..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/discovery/cxx0x.R +++ /dev/null @@ -1,60 +0,0 @@ -#!/bin/env Rscript - -# Copyright (C) 2010 Dirk Eddelbuettel and Romain Francois -# -# This file is part of Rcpp. -# -# Rcpp is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 2 of the License, or -# (at your option) any later version. -# -# Rcpp is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Rcpp. If not, see . - -# This script is used by the Rcpp::RcppCxx0xFlags function to -# generate the "-std=c++0x" flag when the compiler in use is GCC >= 4.3 - -local({ - flag <- function(){ - - cxx0x.code <- ' - #include - #include - - extern "C" SEXP cxx0x(){ - - #ifdef __GNUC__ - #define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) - #if GCC_VERSION >= 40300 - return mkString( "-std=c++0x" ) ; - #endif - #endif - return mkString( "" ) ; - } - ' - td <- tempfile() - dir.create( td ) - here <- getwd() - setwd(td) - dll <- sprintf( "cxx0x%s", .Platform$dynlib.ext ) - on.exit( { - dyn.unload( dll ) - setwd(here) ; - unlink( td, recursive = TRUE ) - } ) - writeLines( cxx0x.code, "cxx0x.cpp" ) - cmd <- sprintf( "%s/R CMD SHLIB cxx0x.cpp", R.home(component="bin") ) - system( cmd, intern = TRUE ) - dyn.load( dll ) - res <- tryCatch( .Call( "cxx0x" ), error = "" ) - res - } - cat( flag() ) -}) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-FAQ.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-FAQ.R deleted file mode 100644 index 04a1de0..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-FAQ.R +++ /dev/null @@ -1,285 +0,0 @@ -### R code from vignette source 'Rcpp-FAQ.Rnw' - -################################################### -### code chunk number 1: Rcpp-FAQ.Rnw:51-56 -################################################### -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -require(Rcpp) -require(inline) -require(highlight) - - -################################################### -### code chunk number 2: Rcpp-FAQ.Rnw:84-86 (eval = FALSE) -################################################### -## vignette("Rcpp-introduction") -## vignette("Rcpp-attributes") - - -################################################### -### code chunk number 3: Rcpp-FAQ.Rnw:213-214 (eval = FALSE) -################################################### -## vignette("Rcpp-package") - - -################################################### -### code chunk number 4: Rcpp-FAQ.Rnw:238-244 -################################################### -fx <- cxxfunction(signature(x = "numeric"), - 'NumericVector xx(x); - return wrap(std::accumulate(xx.begin(), xx.end(), 0.0));', - plugin = "Rcpp") -res <- fx(seq(1, 10, by=0.5)) -res - - -################################################### -### code chunk number 5: Rcpp-FAQ.Rnw:245-246 -################################################### -stopifnot(identical(res, sum(seq(1, 10, by=0.5)))) - - -################################################### -### code chunk number 6: Rcpp-FAQ.Rnw:260-262 (eval = FALSE) -################################################### -## fx <- cxxfunction(signature(), paste(readLines("myfile.cpp"), collapse="\n"), -## plugin = "Rcpp") - - -################################################### -### code chunk number 7: Rcpp-FAQ.Rnw:282-287 -################################################### -cppFunction('double accu(NumericVector x) { - return(std::accumulate(x.begin(), x.end(), 0.0)); -}') -res <- accu(seq(1, 10, by=0.5)) -res - - -################################################### -### code chunk number 18: Rcpp-FAQ.Rnw:715-734 -################################################### -inc <- 'template - class square : public std::unary_function { - public: - T operator()( T t) const { return t*t ;} - }; - ' - -src <- ' - double x = Rcpp::as(xs); - int i = Rcpp::as(is); - square sqdbl; - square sqint; - return Rcpp::DataFrame::create(Rcpp::Named("x", sqdbl(x)), - Rcpp::Named("i", sqint(i))); - ' -fun <- cxxfunction(signature(xs="numeric", is="integer"), - body=src, include=inc, plugin="Rcpp") - -fun(2.2, 3L) - - -################################################### -### code chunk number 21: Rcpp-FAQ.Rnw:815-819 (eval = FALSE) -################################################### -## fx <- cxxfunction(signature(x_="numeric", Y_="matrix", z_="numeric" ), -## paste(readLines("myfile.cpp"), collapse="\n"), -## plugin="RcppArmadillo" ) -## fx(1:4, diag(4), 1:4) - - -################################################### -### code chunk number 22: Rcpp-FAQ.Rnw:821-822 -################################################### -unlink("myfile.cpp") - - -################################################### -### code chunk number 24: Rcpp-FAQ.Rnw:881-888 -################################################### -fx <- cxxfunction(signature(), - 'RNGScope(); - return rnorm(5, 0, 100);', - plugin="Rcpp") -set.seed(42) -fx() -fx() - - -################################################### -### code chunk number 25: Rcpp-FAQ.Rnw:897-904 -################################################### -cppFunction('Rcpp::NumericVector ff(int n) { return rnorm(n, 0, 100); }') -set.seed(42) -ff(5) -ff(5) -set.seed(42) -rnorm(5, 0, 100) -rnorm(5, 0, 100) - - -################################################### -### code chunk number 26: Rcpp-FAQ.Rnw:919-927 -################################################### -src <- 'Rcpp::NumericVector v(4); - v[0] = R_NegInf; // -Inf - v[1] = NA_REAL; // NA - v[2] = R_PosInf; // Inf - v[3] = 42; // see the Hitchhiker Guide - return Rcpp::wrap(v);' -fun <- cxxfunction(signature(), src, plugin="Rcpp") -fun() - - -################################################### -### code chunk number 28: Rcpp-FAQ.Rnw:955-963 (eval = FALSE) -################################################### -## txt <- 'arma::mat Am = Rcpp::as< arma::mat >(A); -## arma::mat Bm = Rcpp::as< arma::mat >(B); -## return Rcpp::wrap( Am * Bm );' -## mmult <- cxxfunction(signature(A="numeric", B="numeric"), -## body=txt, plugin="RcppArmadillo") -## A <- matrix(1:9, 3, 3) -## B <- matrix(9:1, 3, 3) -## C <- mmult(A, B) - - -################################################### -### code chunk number 30: Rcpp-FAQ.Rnw:1010-1028 (eval = FALSE) -################################################### -## ## simple example of seeding RNG and drawing one random number -## gslrng <- ' -## int seed = Rcpp::as(par) ; -## gsl_rng_env_setup(); -## gsl_rng *r = gsl_rng_alloc (gsl_rng_default); -## gsl_rng_set (r, (unsigned long) seed); -## double v = gsl_rng_get (r); -## gsl_rng_free(r); -## return Rcpp::wrap(v);' -## -## plug <- Rcpp:::Rcpp.plugin.maker( -## include.before = "#include ", -## libs = paste("-L/usr/local/lib/R/site-library/Rcpp/lib -lRcpp", -## "-Wl,-rpath,/usr/local/lib/R/site-library/Rcpp/lib", -## "-L/usr/lib -lgsl -lgslcblas -lm")) -## registerPlugin("gslDemo", plug ) -## fun <- cxxfunction(signature(par="numeric"), gslrng, plugin="gslDemo") -## fun(0) - - -################################################### -### code chunk number 31: Rcpp-FAQ.Rnw:1049-1056 (eval = FALSE) -################################################### -## myplugin <- getPlugin("Rcpp") -## myplugin$env$PKG_CXXFLAGS <- "-std=c++11" -## f <- cxxfunction(signature(), settings=myplugin, body=' -## + std::vector x = { 1.0, 2.0, 3.0 }; // fails without -std=c++0x -## + return Rcpp::wrap(x); -## + ') -## f() - - -################################################### -### code chunk number 32: Rcpp-FAQ.Rnw:1072-1084 (eval = FALSE) -################################################### -## src <- ' -## Rcpp::NumericMatrix x(2,2); -## x.fill(42); // or more interesting values -## Rcpp::List dimnms = // two vec. with static names -## Rcpp::List::create(Rcpp::CharacterVector::create("cc", "dd"), -## Rcpp::CharacterVector::create("ee", "ff")); -## // and assign it -## x.attr("dimnames") = dimnms; -## return(x); -## ' -## fun <- cxxfunction(signature(), body=src, plugin="Rcpp") -## fun() - - -################################################### -### code chunk number 34: Rcpp-FAQ.Rnw:1114-1128 (eval = FALSE) -################################################### -## BigInts <- cxxfunction(signature(), -## 'std::vector bigints; -## bigints.push_back(12345678901234567LL); -## bigints.push_back(12345678901234568LL); -## Rprintf("Difference of %ld\\n", 12345678901234568LL - 12345678901234567LL); -## return wrap(bigints);', plugin="Rcpp", includes="#include ") -## -## retval<-BigInts() -## -## # Unique 64-bit integers were cast to identical lower precision numerics -## # behind my back with no warnings or errors whatsoever. Error. -## -## -## stopifnot(length(unique(retval)) == 2) - - -################################################### -### code chunk number 38: Rcpp-FAQ.Rnw:1416-1422 (eval = FALSE) -################################################### -## a <- 1.5:4.5 -## b <- 1.5:4.5 -## implicit_ref(a) -## a -## explicit_ref(b) -## b - - -################################################### -### code chunk number 40: Rcpp-FAQ.Rnw:1454-1461 (eval = FALSE) -################################################### -## a <- 1:5 -## b <- 1:5 -## class(a) -## int_vec_type(a) -## a -## num_vec_type(b) -## b - - -################################################### -### code chunk number 42: Rcpp-FAQ.Rnw:1485-1488 (eval = FALSE) -################################################### -## x <- 1:10 -## const_override_ex(x) -## x - - -################################################### -### code chunk number 46: Rcpp-FAQ.Rnw:1561-1562 (eval = FALSE) -################################################### -## vec_scalar_assign(5L, 3.14) - - -################################################### -### code chunk number 48: Rcpp-FAQ.Rnw:1584-1585 (eval = FALSE) -################################################### -## mat_scalar_assign(2L, 3.0) - - -################################################### -### code chunk number 50: Rcpp-FAQ.Rnw:1628-1629 (eval = FALSE) -################################################### -## test_long_vector_support() - - -################################################### -### code chunk number 52: Rcpp-FAQ.Rnw:1683-1687 (eval = FALSE) -################################################### -## set.seed(123) -## (X <- sample(c(LETTERS[1:5], letters[1:6]), 11)) -## preferred_sort(X) -## stl_sort(X) - - -################################################### -### code chunk number 54: Rcpp-FAQ.Rnw:1720-1723 (eval = FALSE) -################################################### -## x <- c("B", "b", "c", "A", "a") -## sort(x) -## rcpp_sort(x) - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-FAQ.Rnw b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-FAQ.Rnw deleted file mode 100644 index 945e499..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-FAQ.Rnw +++ /dev/null @@ -1,1730 +0,0 @@ -% !Rnw driver = highlight::HighlightWeaveLatex() -\documentclass[10pt]{article} -%\VignetteIndexEntry{Rcpp-FAQ} -%\VignetteEngine{highlight::highlight} -%\VignetteKeywords{Rcpp, FAQ} -%\VignetteDepends{Rcpp} - -\usepackage[USletter]{vmargin} -\setmargrb{0.75in}{0.75in}{0.75in}{0.75in} - -\usepackage{color,alltt} -\usepackage[authoryear,round,longnamesfirst]{natbib} -\usepackage[colorlinks]{hyperref} -\definecolor{link}{rgb}{0,0,0.3} %% next few lines courtesy of RJournal.sty -\hypersetup{ - colorlinks,% - citecolor=link,% - filecolor=link,% - linkcolor=link,% - urlcolor=link -} - -\usepackage{microtype} %% cf http://www.khirevich.com/latex/microtype/ -\usepackage[T1]{fontenc} %% cf http://www.khirevich.com/latex/font/ -\usepackage[bitstream-charter]{mathdesign} %% cf http://www.khirevich.com/latex/font/ - -\newcommand{\proglang}[1]{\textsf{#1}} -\newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}} -\newcommand{\code}[1]{\texttt{#1}} -\newcommand{\R}[0]{\proglang{R}} -\newcommand{\Rs}[0]{\proglang{R }} - -%% defined as a stop-gap measure til interaction with highlight is sorted out -\newcommand{\hlboxlessthan}{ \hlnormalsizeboxlessthan} -\newcommand{\hlboxgreaterthan}{\hlnormalsizeboxgreaterthan} -\newcommand{\hlboxopenbrace}{ \hlnormalsizeboxopenbrace} -\newcommand{\hlboxclosebrace}{ \hlnormalsizeboxclosebrace} -\newcommand{\hlboxbacktick}{ \hlnormalsizeboxbacktick} -\newcommand{\hlboxunderscore}{ \hlnormalsizeboxunderscore} - -%% This corresponds to setting boxes=TRUE for highlight -\newsavebox{\hlbox} -\definecolor{hlBg}{rgb}{0.949019607843137,0.949019607843137,0.949019607843137} -\definecolor{hlBd}{rgb}{0.9,0.9,0.9} % border -\renewenvironment{Hchunk}{\vspace{0.5em}\noindent\begin{lrbox}{\hlbox}\begin{minipage}[b]{.9\textwidth}}% - {\end{minipage}\end{lrbox}\fcolorbox{hlBd}{hlBg}{\usebox{\hlbox}}\vspace{0.5em}} - -\newcommand{\faq}[1]{FAQ~\ref{#1}} -\newcommand{\rdoc}[2]{\href{http://www.rdocumentation.org/packages/#1/functions/#2}{\code{#2}}} - -<>= -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -require(Rcpp) -require(inline) -require(highlight) -@ - -\author{Dirk Eddelbuettel \and Romain Fran\c{c}ois} -\title{Frequently Asked Questions about \pkg{Rcpp}} -\date{\pkg{Rcpp} version \Sexpr{prettyVersion} as of \Sexpr{prettyDate}} - - -\begin{document} -\maketitle - -\abstract{ - \noindent This document attempts to answer the most Frequently Asked - Questions (FAQ) regarding the \pkg{Rcpp} - \citep{CRAN:Rcpp,JSS:Rcpp,Eddelbuettel:2013:Rcpp} package. -} - -\tableofcontents - -\section{Getting started} - -\subsection{How do I get started ?} - -If you have \pkg{Rcpp} installed, please execute the following command in \proglang{R} -to access the introductory vignette (which is a variant of the \citet{JSS:Rcpp} -paper) for a detailed introduction, ideally followed by at least the -Rcpp Attributes \citep{CRAN:Rcpp:Attributes} vignette: - -<>= -vignette("Rcpp-introduction") -vignette("Rcpp-attributes") -@ - -If you do not have \pkg{Rcpp} installed, these documents should also be available -whereever you found this document, \textsl{i.e.,} on every mirror of CRAN site. - -\subsection{What do I need ?} - -Obviously, \proglang{R} must be installed. \pkg{Rcpp} provides a -\proglang{C++} API as an extension to the \proglang{R} system. As such, it -is bound by the choices made by \proglang{R} and is also influenced by how -\proglang{R} is configured. - -In general, the standard environment for building a CRAN package from source -(particularly when it contains \proglang{C} or \proglang{C++} code) is required. This -means one needs: -\begin{itemize} -\item a development environment with a suitable compiler (see - below), header files and required libraries; -\item \proglang{R} should be built in a way that permits linking and possibly - embedding of \proglang{R}; this is typically ensured by the - \texttt{--enable-shared-lib} option; -\item standard development tools such as \texttt{make} etc. -\end{itemize} - -Also see the \href{http://www.rstudio.com/ide/docs/packages/prerequisites}{RStudio - documentation} on pre-requisites for R package development. - -\subsection{What compiler can I use ?} - -On almost all platforms, the GNU Compiler Collection (or \texttt{gcc}, which -is also the name of its \proglang{C} language compiler) has to be used along -with the corresponding \texttt{g++} compiler for the \proglang{C++} language. -A minimal suitable version is a final 4.2.* release; earlier 4.2.* were -lacking some \proglang{C++} features (and even 4.2.1, still used on OS X as the -last gcc release), has issues). - -Generally speaking, the default compilers on all the common platforms are suitable. - -Specific per-platform notes: -\begin{description} - \item[Windows] users need the \texttt{Rtools} package from the site maintained by - Duncan Murdoch which contains all the required tools in a single package; - complete instructions specific to Windows are in the `R Administration' - manual \citep[Appendix D]{R:Administration}. As of August 2014, it still - installs the \texttt{gcc/g++} 4.6.* compiler which limits the ability to use - modern C++ standards so only \code{s-std=c++0x} is supported. R 3.1.0 and - above detect this and set appropriate flags. - \item[OS X] users, as noted in the `R Administration' manual \citep[Appendix - C.4]{R:Administration}, need to install the Apple Developer Tools - (\textsl{e.g.}, \href{https://itunes.apple.com/us/app/xcode/id497799835?mt=12}{Xcode} (OS X $\le 10.8$) or \href{https://developer.apple.com/library/ios/technotes/tn2339/_index.html}{Xcode Command Line Tools} (OS X $\ge 10.9$) (as well as \texttt{gfortran} if \proglang{R} or - Fortran-using packages are to be built); also see \faq{q:OSX} and - \faq{q:OSXArma} below. Depending on whether on OS X release before or after - Mavericks is used, different additional installation may be needed. Consult - the \code{r-sig-mac} list (and its archives) for (current) details. - \item[Linux] user need to install the standard developement packages. Some - distributions provide helper packages which pull in all the required - packages; the \texttt{r-base-dev} package on Debian and Ubuntu is an example. -\end{description} - -The \texttt{clang} and \texttt{clang++} compilers from the LLVM project can -also be used. On Linux, they are inter-operable with \texttt{gcc} et al. On -OS X, they are unfortunately not ABI compatible. The \texttt{clang++} -compiler is interesting as it emits much more comprehensible error messages -than \texttt{g++} (though \texttt{g++} 4.8 and 4.9 have caught up). - -The Intel \texttt{icc} family has also been used successfully as its output -files can also be combined with those from \texttt{gcc}. - -\subsection{What other packages are useful ?} - -Additional packages that we have found useful are - -\begin{description} -\item[\pkg{inline}] which is invaluable for direct compilation, linking and loading - of short code snippets---but now effectively superseded by the Rcpp - Attributes (see \faq{using-attributes} and - \faq{prototype-using-attributes}) feature provided by \pkg{Rcpp}; -\item[\pkg{RUnit}] is used for unit testing; the package is recommended and - will be needed to re-run some of our tests but it is not strictly required - during use of \pkg{Rcpp}; -\item[\pkg{rbenchmark}] to run simple timing comparisons and benchmarks; it is also - recommended but not required. -\item[\pkg{microbenchmark}] is an alternative for benchmarking. -\item[\pkg{devtools}] can help the process of building, compiling and testing - a package but it too is entirely optional. -\end{description} - -\subsection{What licenses can I choose for my code?} - -The \pkg{Rcpp} package is licensed under the terms of the -\href{http://www.gnu.org/licenses/gpl-2.0.html}{GNU GPL 2 or later}, just like -\proglang{R} itself. A key goal of the \pkg{Rcpp} package is to make -extending \proglang{R} more seamless. But by \textsl{linking} your code against -\proglang{R} (as well as \pkg{Rcpp}), the combination is bound by the GPL as -well. This is very clearly -stated at the -\href{https://www.gnu.org/licenses/gpl-faq.html#GPLStaticVsDynamic}{FSF website}: - -\begin{quote} - Linking a GPL covered work statically or dynamically with other modules is - making a combined work based on the GPL covered work. Thus, the terms and - conditions of the GNU General Public License cover the whole combination. -\end{quote} - -So you are free to license your work under whichever terms you find suitable -(provided they are GPL-compatible, see the -\href{http://www.gnu.org/licenses/licenses.html}{FSF site for details}). However, -the combined work will remain under the terms and conditions of the GNU General -Public License. This restriction comes from both \proglang{R} which is GPL-licensed -as well as from \pkg{Rcpp} and whichever other GPL-licensed components you may -be linking against. - - -\section{Compiling and Linking} - -\subsection{How do I use \pkg{Rcpp} in my package ?} -\label{make-package} - -\pkg{Rcpp} has been specifically designed to be used by other packages. -Making a package that uses \pkg{Rcpp} depends on the same mechanics that are -involved in making any \proglang{R} package that use compiled code --- so -reading the \textsl{Writing R Extensions} manual \citep{R:Extensions} is a required -first step. - -Further steps, specific to \pkg{Rcpp}, are described in a separate vignette. - -<>= -vignette("Rcpp-package") -@ - -\subsection{How do I quickly prototype my code?} - -There are two toolchains which can help with this: -\begin{itemize} -\item The older one is provided by the \pkg{inline} package and described in - Section~\ref{using-inline}. -\item Starting with \pkg{Rcpp} 0.10.0, the Rcpp Attributes feature (described - in Section~\ref{using-attributes}) offered an even easier alternative via - the function \rdoc{Rcpp}{evalCpp}, \rdoc{Rcpp}{cppFunction} and - \rdoc{Rcpp}{sourceCpp}. -\end{itemize} -The next two subsections show an example each. - -\subsubsection{Using inline} -\label{using-inline} - -The \pkg{inline} package \citep{CRAN:inline} provides the functions -\rdoc{inline}{cfunction} and \rdoc{inline}{cxxfunction}. Below is a simple -function that uses \texttt{accumulate} from the (\proglang{C++}) Standard -Template Library to sum the elements of a numeric vector. - -<<>>= -fx <- cxxfunction(signature(x = "numeric"), - 'NumericVector xx(x); - return wrap(std::accumulate(xx.begin(), xx.end(), 0.0));', - plugin = "Rcpp") -res <- fx(seq(1, 10, by=0.5)) -res -<>= -stopifnot(identical(res, sum(seq(1, 10, by=0.5)))) -@ - -%\pkg{Rcpp} uses \pkg{inline} to power its entire unit test suite. Consult the -%\texttt{unitTests} directory of \pkg{Rcpp} for several hundred further examples. -% -%< < eval=FALSE>>= -% \list.files( system.file( "unitTests", package = "Rcpp" ), pattern = "^runit[.]" ) -% @ - -One might want to use code that lives in a \proglang{C++} file instead of writing -the code in a character string in R. This is easily achieved by using -\rdoc{base}{readLines}: - -<>= -fx <- cxxfunction(signature(), paste(readLines("myfile.cpp"), collapse="\n"), - plugin = "Rcpp") -@ - -The \texttt{verbose} argument of \rdoc{inline}{cxxfunction} is very -useful as it shows how \pkg{inline} runs the show. - -\subsubsection{Using Rcpp Attributes} -\label{using-attributes} - -Rcpp Attributes \citep{CRAN:Rcpp:Attributes}, and also discussed in -\faq{prototype-using-attributes} below, permits an even easier -route to integrating R and C++. It provides three key functions. First, \rdoc{Rcpp}{evalCpp} -provide a means to evaluate simple C++ expression which is often useful for -small tests, or to simply check if the toolchain is set up -correctly. Second, \rdoc{Rcpp}{cppFunction} can be used to create C++ functions -for R use on the fly. Third, \code{Rcpp}{sourceCpp} can integrate entire files in -order to define multiple functions. - -The example above can now be rewritten as: - -<<>>= -cppFunction('double accu(NumericVector x) { - return(std::accumulate(x.begin(), x.end(), 0.0)); -}') -res <- accu(seq(1, 10, by=0.5)) -res -@ - -The \rdoc{Rcpp}{cppFunction} parses the supplied text, extracts the desired -function names, creates the required scaffolding, compiles, links and loads -the supplied code and makes it available under the selected identifier. - -Similarly, \rdoc{Rcpp}{sourceCpp} can read in a file and compile, link and load -the code therein. - -\subsection{How do I convert my prototyped code to a package ?} -\label{from-inline-to-package} - -Since release 0.3.5 of \pkg{inline}, one can combine \faq{using-inline} and -\faq{make-package}. See \verb|help("package.skeleton-methods")| once -\pkg{inline} is loaded and use the skeleton-generating functionality to -transform a prototyped function into the minimal structure of a package. -After that you can proceed with working on the package in the spirit of -\faq{make-package}. - -Rcpp Attributes \citep{CRAN:Rcpp:Attributes} also offers a means to convert -functions written using Rcpp Attributes into a function via the -\rdoc{Rdoc}{compileAttributes} function; see the vignette for details. - -\subsection{How do I quickly prototype my code in a package?} -\label{using-a-package} - -The simplest way may be to work directly with a package. Changes to both the -\proglang{R} and \proglang{C++} code can be compiled and tested from the -command line via: - -<>= -$ R CMD INSTALL mypkg && Rscript --default-packages=mypkg -e 'someFunctionToTickle(3.14)' -@ - -This first installs the packages, and then uses the command-line tool -\rdoc{utils}{Rscript} (which ships with \code{R}) to load the package, and execute -the \proglang{R} expression following the \code{-e} switch. Such an -expression can contain multiple statements separated by semicolons. -\rdoc{utils}{Rscript} is available on all three core operating systems. - -On Linux, one can also use \code{r} from the \code{littler} package by Horner -and Eddelbuettel which is an alternative front end to \proglang{R} designed -for both \verb|#!| (hashbang) scripting and command-line use. It has slightly -faster start-up times than \rdoc{utils}{Rscript}; and both give a guaranteed clean -slate as a new session is created. - -The example then becomes - -<>= -$ R CMD INSTALL mypkg && r -l mypkg -e 'someFunctionToTickle(3.14)' -@ - -The \code{-l} option calls 'suppressMessages(library(mypkg))' before executing the -\proglang{R} expression. Several packages can be listed, separated by a comma. - -More choice are provide by the \pkg{devtools} package, and by using -RStudio. See the respective documentation for details. - -\subsection{But I want to compile my code with R CMD SHLIB !} -\label{using-r-cmd-shlib} - -The recommended way is to create a package and follow \faq{make-package}. The -alternate recommendation is to use \pkg{inline} and follow \faq{using-inline} -because it takes care of all the details. - -However, some people have shown that they prefer not to follow recommended -guidelines and compile their code using the traditional \texttt{R CMD SHLIB}. To -do so, we need to help \texttt{SHLIB} and let it know about the header files -that \pkg{Rcpp} provides and the \proglang{C++} library the code must link -against. - -On the Linux command-line, you can do the following:\newline -<>= -$ export PKG_LIBS=`Rscript -e "Rcpp:::LdFlags()"` # if Rcpp older than 0.11.0 -$ export PKG_CXXFLAGS=`Rscript -e "Rcpp:::CxxFlags()"` -$ R CMD SHLIB myfile.cpp -@ -which first defines and exports two relevant environment variables which -\texttt{R CMD SHLIB} then relies on. On other operating systems, appropriate -settings may have to be used to define the environment variables. - -This approach corresponds to the very earliest ways of building programs and -can still be found in some deprecated documents (as \textit{e.g.} some of -Dirk's older 'Intro to HPC with R' tutorial slides). It is still not -recommended as there are tools and automation mechanisms that can do the work -for you. - -\pkg{Rcpp} versions 0.11.0 or later can do with the definition of -\code{PKG\_LIBS} as a user-facing library is no longer needed (and hence no -longer shipped with the package). One still needs to set \code{PKG\_CXXFLAGS} -to tell R where the \pkg{Rcpp} headers files are located. - -Once \code{R CMD SHLIB} has created the dyanmically-loadable file (with -extension \code{.so} on Linux, \code{.dylib} on OS X or \code{.dll} on -Windows), it can be loaded in an R session via \rdoc{base}{dyn.load}, and the -function can be executed via \rdoc{base}{.Call}. Needless to say, we -\emph{strongly} recommend using a package, or at least Rcpp Attributes as -either approach takes care of a lot of these tedious and error-prone manual -steps. - - -\subsection{But R CMD SHLIB still does not work !} - -We have had reports in the past where build failures occurred when users had -non-standard code in their \verb|~/.Rprofile| or \texttt{Rprofile.site} (or -equivalent) files. - -If such code emits text on \texttt{stdout}, the frequent and implicit -invocation of \texttt{Rscript -e "..."} (as in \faq{using-r-cmd-shlib} -above) to retrieve settings directly from \pkg{Rcpp} will fail. - -You may need to uncomment such non-standard code, or protect it by wrapping -it inside \texttt{if (interactive())}, or possibly try to use \texttt{Rscript - --vanilla} instead of plain \texttt{Rscript}. - - -\subsection{What about \texttt{LinkingTo} ?} - -\proglang{R} has only limited support for cross-package linkage. - -We now employ the \texttt{LinkingTo} field of the \texttt{DESCRIPTION} file -of packages using \pkg{Rcpp}. But this only helps in having \proglang{R} -compute the location of the header files for us. - -The actual library location and argument still needs to be provided by the -user. How to do so has been shown above, and we recommned you use either -\faq{make-package} or \faq{using-inline} both which use the \pkg{Rcpp} -function \texttt{Rcpp:::LdFlags()}. - -If and when \texttt{LinkingTo} changes and lives up to its name, we will be -sure to adapt \pkg{Rcpp} as well. - -An important change arrive with \pkg{Rcpp} release 0.11.0 and concern the -automatic registration of functions; see Section~\ref{function-registration} below. - - -\subsection{Does \pkg{Rcpp} work on windows ?} - -Yes of course. See the Windows binaries provided by CRAN. - -\subsection{Can I use \pkg{Rcpp} with Visual Studio ?} - -Not a chance. - -And that is not because we are meanies but because \proglang{R} and Visual -Studio simply do not get along. As \pkg{Rcpp} is all about extending -\proglang{R} with \proglang{C++} interfaces, we are bound by the available -toolchain. And \proglang{R} simply does not compile with Visual Studio. Go -complain to its vendor if you are still upset. - -\subsection{I am having problems building Rcpp on OS X, any help ?} -\label{q:OSX} - -There are three known issues regarding Rcpp build problems on OS X. If you are -building packages with RcppArmadillo, there is yet another issue that is -addressed separately in \faq{q:OSXArma} below. - -\subsubsection{Lack of a Compiler} -By default, OS X does not ship with an active compiler. To enable a compiler one -must either install -\href{https://itunes.apple.com/us/app/xcode/id497799835?mt=12}{Xcode} (OS X -$\le 10.8$) or -\href{https://developer.apple.com/library/ios/technotes/tn2339/_index.html}{Xcode - Command Line Tools} (OS X $\ge 10.9$). We will focus on the later as the -installation requires the use of \texttt{Terminal} and the install size is -significantly less than the prior, which is setup using an installer. - -To install XCode Command Line Tools, one must do the following: - -\begin{enumerate} - \item Open \texttt{Terminal} found in \texttt{/Applications/Utilities/} - \item Type the following: - -<>= -$ xcode-select --install -@ - \item Press "Install" on the window that pops up. - \item After the installation is complete, type the following in \texttt{Terminal} to ensure the installation was successful: - -<>= -$ gcc --version -@ -\end{enumerate} - -After major system updates, e.g. going from version 10.11 to 10.12, you may need -to accept the terms and licenses associated the the Xcode command line tools -prior to being allowed to compile again. - -To do so, open the \texttt{Terminal} found in \texttt{/Applications/Utilities/} and type: - -<>= -$ git -@ - -Press spacebar to move down to the end of the file. There, you should see a -prompt asking whether or not you accept the terms via either "Yes" or -"No". Enter "Yes" if you agree to the terms to have the command line tools -reactivated. - -\subsubsection{Differing Mac OS X R Versions Leading to Binary Failures} - -There are currently two distinct versions of R for OS X. The first version is a -legacy version meant for Mac OS X 10.6 (Snow Leopard) - 10.8 (Mountain -Lion). The second version is for more recent system Mac OS X 10.9 (Mavericks), -10.10 (Yosemite), 10.11 (El Capitan). The distinction comes as a result of a -change in the compilers shipped with the operating system. As a result, avoid -sending package binaries if it is known that your collaborators are working on -older systems as the R binaries for these two versions will not be able to mix. - -\subsubsection{No OpenMP Support} -The OS X operating environment lacks the ability to parallelize sections of code -using the \href{http://openmp.org/wp/}{OpenMP} standard. As a result, make sure -to protect any reference to OpenMP. In this case, protect the inclusion of -headers with: - -<>= -#ifdef _OPENMP - #include -#endif -@ - -And when one goes to parallelize portions of code use: - -<>= -#ifdef _OPENMP - // multithreaded OpenMP version of code -#else - // single-threaded version of code -#endif -@ - -Doing so will enable the parallelization of the process on Linux and Windows. In -the event that Apple enables OpenMP later on, this code will also allow for -parallelization to occur. - -The reason for the lack of OpenMP support is because under OS X, you are not -using the \texttt{gcc} compiler. Instead, all the requests are being redirected -to \texttt{llvm}. As of LLVM 3.7, the -\href{https://clang-omp.github.io/}{community initiative} to enable OpenMP has -been merged into the \href{http://openmp.llvm.org/}{official branch}. Thus, -there is hope in the next release of Xcode (around WWDC in June 2016) that -OpenMP will work on OS X. - - -\subsubsection{Additional Information / Help} - -Below are additional resources that provide information regarding compiling Rcpp code on OS X. - -\begin{enumerate} - \item A helpful post was provided by Brian Ripley regarding the use of - compiling R code with OS X in April 2014 - \href{https://stat.ethz.ch/pipermail/r-sig-mac/2014-April/010835.html}{on - the \code{r-sig-mac} list}, which is generally recommended for OS - X-specific questions and further consultation. - \item Another helpful write-up for installation / compilation on OS X Mavericks is provided - \href{http://www.bioconductor.org/developers/how-to/mavericks-howto/}{by the BioConductor project}. - \item Lastly, another resource that exists for installation / compilation - help is provided at - \url{http://thecoatlessprofessor.com/programming/r-compiler-tools-for-rcpp-on-os-x/}. -\end{enumerate} - -\textbf{Note:} If you are running into trouble compiling code with RcppArmadillo, please also see \faq{q:OSXArma} listed below. - -%At the time of writing this paragraph (in the spring of 2011), \pkg{Rcpp} -%(just like CRAN) supports all OS X releases greater or equal to 10.5. -%However, building \pkg{Rcpp} from source (or building packages using -%\pkg{Rcpp}) also requires a recent-enough version of Xcode. For the -%\textsl{Leopard} release of OS X, the current version is 3.1.4 which can be -%downloaded free of charge from the Apple Developer site. Users may have to -%manually select \code{g++-4.2} via the symbolic link \code{/usr/bin/g++}. -%The \textsl{Snow Leopard} release already comes with Xcode 3.2.x and work as -%is. - -\subsection{Does \pkg{Rcpp} work on solaris/suncc ?} - -Yes, it generally does. But as we do not have access to such systems, some -issues persist on the CRAN test systems. - -\subsection{Does \pkg{Rcpp} work with Revolution R ?} - -We have not tested it yet. \pkg{Rcpp} might need a few tweaks to work -with the compilers used by Revolution R (if those differ from the defaults). - -\subsection{Is it related to CXXR ?} - -CXXR is an ambitious project that aims to totally refactor the \proglang{R} -interpreter in \proglang{C++}. There are a few similaritites with \pkg{Rcpp} -but the projects are unrelated. - -CXXR and \pkg{Rcpp} both want \proglang{R} to make more use of \proglang{C++} -but they do it in very different ways. - -\subsection{How do I quickly prototype my code using Attributes?} -\label{prototype-using-attributes} - -\pkg{Rcpp} version 0.10.0 and later offer a new feature 'Rcpp Attributes' -which is described in detail in its own vignette -\citep{CRAN:Rcpp:Attributes}. In short, it offers functions \rdoc{Rcpp}{evalCpp}, -\rdoc{Rcpp}{cppFunction} and \rdoc{Rcpp}{sourceCpp} which extend the functionality of the -\rdoc{Rcpp}{cxxfunction} function. - - -\subsection{What about the new 'no-linking' feature??} -\label{function-registration} - -Starting with \pkg{Rcpp} 0.11.0, functionality provided by \pkg{Rcpp} and -used by packages built with \pkg{Rcpp} accessed via the registration facility -offered by R (and which is used by \pkg{lme4} and \pkg{Matrix}, as well as by -\pkg{xts} and \pkg{zoo}). This requires no effort from the user / -programmer, and even frees us from explicit linking instruction. In most -cases, the files \code{src/Makevars} and \code{src/Makevars.win} can now be -removed. Exceptions are the use of \pkg{RcppArmadillo} (which needs an entry -\verb|PKG_LIBS=$(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS)|) and packages linking -to external libraries they use. - -But for most packages using \pkg{Rcpp}, only two things are required: -\begin{itemize} -\item an entry in \code{DESCRIPTION} such as \code{Imports: Rcpp} (which may - be versioned as in \code{Imports: Rcpp (>= 0.11.0)}), and -\item an entry in \code{NAMESPACE} to ensure \pkg{Rcpp} is correctly - instantiated, for example \code{importFrom(Rcpp, evalCpp)}. -\end{itemize} - -The name of the symbol does not really matter; once one symbol is imported all -symbols should be available. - -\subsection{I am having problems building RcppArmadillo on OS X, any help ?} -\label{q:OSXArma} - -Odds are your build failures are due to the absence of \texttt{gfortran} -and its associated libraries. The errors that you may receive are related to either: -\begin{center} -\textbf{``-lgfortran''} or \textbf{``-lquadmath''} -\end{center} - -To rectify the root of these errors, there are two options available. The first option is to download and use a fixed set of \texttt{gfortran} binaries that are used to compile R for OS X (e.g. given by the maintainers of the OS X build). The second option is to either use pre-existing \texttt{gfortran} binaries on your machine or download the latest. - -\subsubsection{Fixed set of \texttt{gfortran} binaries} - -Within this option, you will install a pre-compiled \code{gfortran} binary from -\href{http://r.research.att.com/libs/}{\texttt{r.research.att.com/libs/}}. The binary listed here was compiled by Simon Urbanek the maintainer of the OS X R versions. - -To install the pre-compiled \code{gfortran} binary, do the following: -\begin{enumerate} - \item Open \texttt{Terminal} found in \texttt{/Applications/Utilities/} - \item Type the following: - -<>= -curl -O http://r.research.att.com/libs/gfortran-4.8.2-darwin13.tar.bz2 -sudo tar fvxz gfortran-4.8.2-darwin13.tar.bz2 -C / -@ - -\end{enumerate} - -For more information on this error, please see TheCoatlessProfessor's \href{http://thecoatlessprofessor.com/programming/rcpp-rcpparmadillo-and-os-x-mavericks-lgfortran-and-lquadmath-error/}{Rcpp, RcppArmadillo and OS X Mavericks "-lgfortran" and "-lquadmath" error}. - -\subsubsection{Pre-existing or latest \texttt{gfortran} binaries} - -Most OS X users that have a pre-existing \texttt{gfortran} binaries or want the latest version, typically use a custom packaging solution to install \texttt{gfortran}; -\href{https://www.macports.org/}{\texttt{macports}}, -\href{http://brew.sh/}{\texttt{homebrew}}, and -\href{http://www.finkproject.org/}{\texttt{fink}} are the usual suspects -here. In general, we recommend using homebrew, and we provide a short -set of instructions for installing \texttt{gfortran} below. - -After installing \texttt{homebrew} by -\href{http://brew.sh/}{following the instructions here}, -you can install the latest version of \texttt{gfortran} with: - - \code{brew install gcc} - -Note that \texttt{gfortran} is available as part of the \texttt{gcc} -'formula' by default and cannot be downloaded separately, but one can -freely use \texttt{gfortran} with Apple (or LLVM) \texttt{clang} -compilers (as used by default on OS X since Mavericks). - -You may need to set the \code{FLIBS} variable in your -\texttt{~/.R/Makevars} to point to the location of the \texttt{gfortran} -library paths. A solution is outlined -\href{http://stackoverflow.com/questions/29992066/rccp-warning-directory-not-found-for-option-l-usr-local-cellar-gfortran-4-8/29993906#29993906}{on - StackOverflow}, but the relevant details are copied in brief here. - -In short, you want to add this entry to your \texttt{~/.R/Makevars}: - -<>= -FLIBS=`gfortran -print-search-dirs | grep ^libraries: | sed 's|libraries: =||' | sed 's|:| -L|g' | sed 's|^|-L|'` -@ - -This invocation explicitly asks and constructs the library link paths -from the \texttt{gfortran}'s reported search paths, and produces a set -of paths suitable to be passed to \code{FLIBS}. \R will then search -these paths when attempting to locate e.g \code{libgfortran} when -compiling \pkg{RcppArmadillo} or other FORTRAN-dependent code. - -Also see \faq{q:OSX} above, and the links provided in that answer. In the event -the above solution does not satisfy all the OS X build problems. - -\section{Examples} - -The following questions were asked on the -\href{https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel}{Rcpp-devel} -mailing list, which is our preferred place to ask questions as it guarantees -exposure to a number of advanced Rcpp users. The -\href{http://stackoverflow.com/questions/tagged/rcpp}{StackOverflow tag for - rcpp} is an alternative; that site is also easily searchable. - -Several dozen fully documented examples are provided at the -\href{http://gallery.rcpp.org}{Rcpp Gallery} -- which is also open for new contributions. - - -\subsection{Can I use templates with \pkg{Rcpp} ? } - -\begin{quote} - \emph{I'm curious whether one can provide a class definition inline in an R - script and then initialize an instance of the class and call a method on - the class, all inline in R.} -\end{quote} - -This question was initially about using templates with \pkg{inline}, and we -show that (older) answer first. It is also easy with Rcpp Attributes which is -what we show below. - -\subsubsection{Using inline} - -\noindent Most certainly, consider this simple example of a templated class -which squares its argument: - -<>= -inc <- 'template - class square : public std::unary_function { - public: - T operator()( T t) const { return t*t ;} - }; - ' - -src <- ' - double x = Rcpp::as(xs); - int i = Rcpp::as(is); - square sqdbl; - square sqint; - return Rcpp::DataFrame::create(Rcpp::Named("x", sqdbl(x)), - Rcpp::Named("i", sqint(i))); - ' -fun <- cxxfunction(signature(xs="numeric", is="integer"), - body=src, include=inc, plugin="Rcpp") - -fun(2.2, 3L) -@ - -\subsubsection{Using Rcpp Attributes} - -We can also use 'Rcpp Attributes' \citep{CRAN:Rcpp:Attributes}---as described -in \faq{using-attributes} and \faq{prototype-using-attributes} above. Simply -place the following code into a file and use \rdoc{Rcpp}{sourceCpp} on it. It -will even run the R part at the end. - -<>= -#include - -template class square : public std::unary_function { -public: - T operator()( T t) const { return t*t ;} -}; - -// [[Rcpp::export]] -Rcpp::DataFrame fun(double x, int i) { - square sqdbl; - square sqint; - return Rcpp::DataFrame::create(Rcpp::Named("x", sqdbl(x)), - Rcpp::Named("i", sqint(i))); -} - -/*** R -fun(2.2, 3L) -*/ -@ - -\subsection{Can I do matrix algebra with \pkg{Rcpp} ?} -\label{matrix-algebra} - -\begin{quote} - \emph{\pkg{Rcpp} allows element-wise operations on vector and matrices through - operator overloading and STL interface, but what if I want to multiply a - matrix by a vector, etc ...} -\end{quote} - -\noindent Currently, \pkg{Rcpp} does not provide binary operators to allow operations -involving entire objects. Adding operators to \pkg{Rcpp} would be a major -project (if done right) involving advanced techniques such as expression -templates. We currently do not plan to go in this direction, but we would -welcome external help. Please send us a design document. - -However, we have developed the \pkg{RcppArmadillo} package -\citep{CRAN:RcppArmadillo,Eddelbuettel+Sanderson:2014:RcppArmadillo} that -provides a bridge between \pkg{Rcpp} and \pkg{Armadillo} -\citep{Sanderson:2010:Armadillo}. \pkg{Armadillo} -supports binary operators on its types in a way that takes full advantage of -expression templates to remove temporaries and allow chaining of -operations. That is a mouthful of words meaning that it makes the code go -faster by using fiendishly clever ways available via the so-called template -meta programming, an advanced \proglang{C++} technique. -Also, the \pkg{RcppEigen} package \citep{JSS:RcppEigen} provides an alternative using the -\href{http://eigen.tuxfamily.org}{Eigen} template library. - -\subsubsection{Using inline} - -The following example is adapted from the examples available at the project -page of Armadillo. It calculates $ x' \times Y^{-1} \times z$ - -<>= - // copy the data to armadillo structures - arma::colvec x = Rcpp::as (x_); - arma::mat Y = Rcpp::as(Y_) ; - arma::colvec z = Rcpp::as(z_) ; - - // calculate the result - double result = arma::as_scalar(arma::trans(x) * arma::inv(Y) * z); - - // return it to R - return Rcpp::wrap( result ); -@ - -%% Running this now makes the package depend on RcppArmadillo being installed -%% and would require at least a Suggests - -If stored in a file \code{myfile.cpp}, we can use it via \pkg{inline}: - -<>= -fx <- cxxfunction(signature(x_="numeric", Y_="matrix", z_="numeric" ), - paste(readLines("myfile.cpp"), collapse="\n"), - plugin="RcppArmadillo" ) -fx(1:4, diag(4), 1:4) -@ -<>= -unlink("myfile.cpp") -@ - -The focus is on the code \verb|arma::trans(x) * arma::inv(Y) * z|, which -performs the same operation as the R code \verb|t(x) %*% solve(Y) %*% z|, -although Armadillo turns it into only one operation, which makes it quite fast. -Armadillo benchmarks against other \proglang{C++} matrix algebra libraries -are provided on \href{http://arma.sourceforge.net/speed.html}{the Armadillo website}. - -It should be noted that code below depends on the version \texttt{0.3.5} of -\pkg{inline} and the version \texttt{0.2.2} of \pkg{RcppArmadillo} - -\subsubsection{Using Rcpp Attributes} - -We can also write the same example for use with Rcpp Attributes: - -<>= -#include - -// [[Rcpp::depends(RcppArmadillo)]] - -// [[Rcpp::export]] -double fx(arma::colvec x, arma::mat Y, arma::colvec z) { - // calculate the result - double result = arma::as_scalar(arma::trans(x) * arma::inv(Y) * z); - return result; -} - -/*** R -fx(1:4, diag(4), 1:4) -*/ -@ - -Here, the additional \code{Rcpp::depends(RcppArmadillo)} ensures that code -can be compiled against the \pkg{RcppArmadillo} header, and that the correct -libraries are linked to the function built from the supplied code example. - -Note how we do not have to concern ourselves with conversion; R object -automatically become (Rcpp)Armadillo objects and we can focus on the single -computing a (scalar) result. - - - -\subsection{Can I use code from the Rmath header and library with \pkg{Rcpp} ?} - -\begin{quote} - \emph{Can I call functions defined in the Rmath header file and the - standalone math library for R--as for example the random number generators?} -\end{quote} - -\noindent Yes, of course. This math library exports a subset of R, but \pkg{Rcpp} has -access to much more. Here is another simple example. Note how we have to use -and instance of the \texttt{RNGScope} class to set and re-set the -random-number generator. This also illustrates Rcpp sugar as we are using a -vectorised call to \texttt{rnorm}. Moreover, because the RNG is reset, the -two calls result in the same random draws. If we wanted to control the draws, -we could explicitly set the seed after the \texttt{RNGScope} object has been -instantiated. - -<<>>= -fx <- cxxfunction(signature(), - 'RNGScope(); - return rnorm(5, 0, 100);', - plugin="Rcpp") -set.seed(42) -fx() -fx() -@ - -Newer versions of Rcpp also provide the actual Rmath function in the \code{R} -namespace, \textsl{i.e.} as \code{R::rnorm(m,s)} to obtain a scalar -random variable distributed as $N(m,s)$. - -Using Rcpp Attributes, this can be as simple as - -<<>>= -cppFunction('Rcpp::NumericVector ff(int n) { return rnorm(n, 0, 100); }') -set.seed(42) -ff(5) -ff(5) -set.seed(42) -rnorm(5, 0, 100) -rnorm(5, 0, 100) -@ - -This illustrates the Rcpp Attributes adds the required \code{RNGScope} object -for us. It also shows how setting the seed from R affects draws done via C++ -as well as R, and that identical random number draws are obtained. - -\subsection{Can I use NA and Inf with \pkg{Rcpp} ?} - -\begin{quote} - \emph{R knows about NA and Inf. How do I use them from C++?} -\end{quote} - -\noindent Yes, see the following example: - -<<>>= -src <- 'Rcpp::NumericVector v(4); - v[0] = R_NegInf; // -Inf - v[1] = NA_REAL; // NA - v[2] = R_PosInf; // Inf - v[3] = 42; // see the Hitchhiker Guide - return Rcpp::wrap(v);' -fun <- cxxfunction(signature(), src, plugin="Rcpp") -fun() -@ - -Similarly, for Rcpp Attributes: - -<>= -#include - -// [[Rcpp::export]] -Rcpp::NumericVector fun(void) { - Rcpp::NumericVector v(4); - v[0] = R_NegInf; // -Inf - v[1] = NA_REAL; // NA - v[2] = R_PosInf; // Inf - v[3] = 42; // see the Hitchhiker Guide - return v; -} -@ - -\subsection{Can I easily multiply matrices ?} - -\begin{quote} - \emph{Can I multiply matrices easily?} -\end{quote} - -\noindent Yes, via the \pkg{RcppArmadillo} package which builds upon \pkg{Rcpp} and the -wonderful Armadillo library described above in \faq{matrix-algebra}: - -<>= -txt <- 'arma::mat Am = Rcpp::as< arma::mat >(A); - arma::mat Bm = Rcpp::as< arma::mat >(B); - return Rcpp::wrap( Am * Bm );' -mmult <- cxxfunction(signature(A="numeric", B="numeric"), - body=txt, plugin="RcppArmadillo") -A <- matrix(1:9, 3, 3) -B <- matrix(9:1, 3, 3) -C <- mmult(A, B) -@ -% < < echo=FALSE,print=FALSE > > = -% A <- matrix(1:9, 3, 3) -% B <- matrix(9:1, 3, 3) -% A %*% B -% @ - -Armadillo supports a full range of common linear algebra operations. - -The \pkg{RcppEigen} package provides an alternative using the -\href{http://eigen.tuxfamily.org}{Eigen} template library. - -Rcpp Attributes, once again, makes this even easier: - -<>= - -#include - -// [[Rcpp::depends(RcppArmadillo)]] - -// [[Rcpp::export]] -arma::mat mult(arma::mat A, arma::mat B) { - return A*B; -} - -/*** R -A <- matrix(1:9, 3, 3) -B <- matrix(9:1, 3, 3) -mult(A,B) -*/ -@ - -which can be built, and run, from R via a simple \rdoc{Rcpp}{sourceCpp} -call---and will also run the small R example at the end. - - -\subsection{How do I write a plugin for \pkg{inline} and/or Rcpp Attributes?} - -\begin{quote} - \emph{How can I create my own plugin for use by the \pkg{inline} package?} -\end{quote} - -\noindent Here is an example which shows how to it using GSL libraries as an -example. This is merely for demonstration, it is also not perfectly general -as we do not detect locations first---but it serves as an example: - -<>= -## simple example of seeding RNG and drawing one random number -gslrng <- ' -int seed = Rcpp::as(par) ; -gsl_rng_env_setup(); -gsl_rng *r = gsl_rng_alloc (gsl_rng_default); -gsl_rng_set (r, (unsigned long) seed); -double v = gsl_rng_get (r); -gsl_rng_free(r); -return Rcpp::wrap(v);' - -plug <- Rcpp:::Rcpp.plugin.maker( - include.before = "#include ", - libs = paste("-L/usr/local/lib/R/site-library/Rcpp/lib -lRcpp", - "-Wl,-rpath,/usr/local/lib/R/site-library/Rcpp/lib", - "-L/usr/lib -lgsl -lgslcblas -lm")) -registerPlugin("gslDemo", plug ) -fun <- cxxfunction(signature(par="numeric"), gslrng, plugin="gslDemo") -fun(0) -@ -% - -Here the \pkg{Rcpp} function \code{Rcpp.plugin.maker} is used to create a -plugin 'plug' which is then registered, and subsequently used by \pkg{inline}. - -The same plugins can be used by Rcpp Attributes as well. - -\subsection{How can I pass one additional flag to the compiler?} - -\begin{quote} - \emph{How can I pass another flag to the \code{g++} compiler without writing a new plugin?} -\end{quote} - -The quickest way is to modify the return value from an existing plugin. Here -we use the default one from \pkg{Rcpp} itself in order to pass the new flag -\verb|-std=c++0x|. As it does not set the \verb|PKG_CXXFLAGS| variable, we -simply assign this. For other plugins, one may need to append to the existing -values instead. - -<>= -myplugin <- getPlugin("Rcpp") -myplugin$env$PKG_CXXFLAGS <- "-std=c++11" -f <- cxxfunction(signature(), settings=myplugin, body=' -+ std::vector x = { 1.0, 2.0, 3.0 }; // fails without -std=c++0x -+ return Rcpp::wrap(x); -+ ') -f() -@ - -For Rcpp Attributes, the attributes \code{Rcpp::plugin()} can be -used. Currently supported plugins are for C++11 as well as for OpenMP. - -\subsection{How can I set matrix row and column names ?} - -\begin{quote} - \emph{Ok, I can create a matrix, but how do I set its row and columns names?} -\end{quote} - -Pretty much the same way as in \proglang{R} itself: We define a list with two -character vectors, one each for row and column names, and assign this to the -\code{dimnames} attribute: - -<>= -src <- ' - Rcpp::NumericMatrix x(2,2); - x.fill(42); // or more interesting values - Rcpp::List dimnms = // two vec. with static names - Rcpp::List::create(Rcpp::CharacterVector::create("cc", "dd"), - Rcpp::CharacterVector::create("ee", "ff")); - // and assign it - x.attr("dimnames") = dimnms; - return(x); -' -fun <- cxxfunction(signature(), body=src, plugin="Rcpp") -fun() -@ -% - -The same logic, but used with Rcpp Attributes: - -<>= -#include - -// [[Rcpp::export]] -Rcpp::List fun(void) { - Rcpp::NumericMatrix x(2,2); - x.fill(42); // or more interesting values - Rcpp::List dimnms = // two vec. with static names - Rcpp::List::create(Rcpp::CharacterVector::create("cc", "dd"), - Rcpp::CharacterVector::create("ee", "ff")); - // and assign it - x.attr("dimnames") = dimnms; - return(x); -} -@ - -\subsection{Why can long long types not be cast correctly?} - -That is a good and open question. We rely on the basic \proglang{R} types, -notably \code{integer} and \code{numeric}. These can be cast to and from -\proglang{C++} types without problems. But there are corner cases. The -following example, contributed by a user, shows that we cannot reliably cast -\code{long} types (on a 64-bit machines). - -<>= -BigInts <- cxxfunction(signature(), - 'std::vector bigints; - bigints.push_back(12345678901234567LL); - bigints.push_back(12345678901234568LL); - Rprintf("Difference of %ld\\n", 12345678901234568LL - 12345678901234567LL); - return wrap(bigints);', plugin="Rcpp", includes="#include ") - -retval<-BigInts() - -# Unique 64-bit integers were cast to identical lower precision numerics -# behind my back with no warnings or errors whatsoever. Error. - - -stopifnot(length(unique(retval)) == 2) -@ -% - -While the difference of one is evident at the \proglang{C++} level, it is no -longer present once cast to \proglang{R}. The 64-bit integer values get cast -to a floating point types with a 53-bit mantissa. We do not have a good -suggestion or fix for casting 64-bit integer values: 32-bit integer values -fit into \code{integer} types, up to 53 bit precision fits into -\code{numeric} and beyond that truly large integers may have to converted -(rather crudely) to text and re-parsed. Using a different representation as -for example from the \href{http://gmplib.org/}{GNU Multiple Precision Arithmetic - Library} may be an alternative. - -\subsection{What LaTeX packages do I need to typeset the vignettes ?} - -\begin{quote} - \emph{I would like to typeset the vignettes. What do I need?} -\end{quote} - -The \href{https://www.tug.org/texlive/}{TeXLive} distribution seems to get -bigger and bigger. What you need to install may depend on your operating -system. - -Specific per-platform notes: -\begin{description} - \item[Windows] users probably want the \href{http://miktex.org/}{MiKTeX}. - Suggestions for a more detailed walk through would be appreciated. - \item[OS X] users seem to fall into camps which like or do not like brew / - homebrew. One suggestion was to install - \href{https://tug.org/mactex/mactex-download.html}{MacTeX} but at - approximately 2.5gb (as of January 2016) this is not lightweight. - \item[Linux] users probably want the full - \href{https://www.tug.org/texlive/}{TeXLive} set from their distribution. On - \href{http://www.debian.org}{Debian} these packages are installed to build - the R package itself: \texttt{texlive-base, texlive-latex-base, - texlive-generic-recommended, texlive-fonts-recommended, - texlive-fonts-extra, texlive-extra-utils, texlive-latex-recommended, - texlive-latex-extra}. Using \texttt{texlive-full} may be a shortcut. - Fedora and other distributions should have similar packages. -\end{description} - -\subsection{Why is there a limit of 20 on some constructors?} - -\begin{quote} - \emph{Ok, I would like to pass $N$ object but you only allow 20. How come?} -\end{quote} - -In essence, and in order to be able to compile it with the largest number of -compilers, \pkg{Rcpp} is constrained by the older C++ standards which do not -support variadic function arguments. So we actually use macros and code -generator scripts to explicitly enumerate arguments, and that number has to stop -at some limit. We chose 20. - -A good discussion is available at -\href{http://stackoverflow.com/questions/27371543}{this StackOverflow question} -concering data.frame creation with \pkg{Rcpp}. One solution offers a custom -\code{ListBuilder} class to circumvent the limit; another suggests to simply -nest lists. - -\subsection{Can I use default function parameters with \pkg{Rcpp}?} - -Yes, you can use default parameters with \textit{some} limitations. -The limitations are mainly related to string literals and empty vectors. -This is what is currently supported: - -\begin{itemize} -\item String literals delimited by quotes (e.g. \code{"foo"}) -\item Integer and Decimal numeric values (e.g. \code{10} or \code{4.5}) -\item Pre-defined constants including: -\begin{itemize} -\item Booleans: \code{true} and \code{false} -\item Null Values: \code{R\_NilValue}, \code{NA\_STRING}, -\code{NA\_INTEGER}, \code{NA\_REAL}, and \code{NA\_LOGICAL}. -\end{itemize} -\item Selected vector types can be instantiated using the empty form of the -\code{::create} static member function. -\begin{itemize} -\item \code{CharacterVector}, \code{IntegerVector}, and -\code{NumericVector} -\end{itemize} -\item Matrix types instantiated using the rows, cols constructor \code{Rcpp::Matrix n(rows,cols)} -\begin{itemize} -\item \code{CharacterMatrix}, \code{IntegerMatrix}, and -\code{NumericMatrix}) -\end{itemize} -\end{itemize} - -To illustrate, please consider the following example that provides a short -how to: - -<>= -#include - -// [[Rcpp::export]] -void sample_defaults(NumericVector x = NumericVector::create(), // Size 0 vector - bool bias = true, // Set to true - std::string method = "rcpp rules!"){ // Default string - Rcpp::Rcout << "x size: " << x.size() << ", "; - Rcpp::Rcout << "bias value: " << bias << ", "; - Rcpp::Rcout << "method value: " << method << std::endl; -} - -/*** R -sample_defaults() # all defaults -sample_defaults(1:5) # supply x values -sample_defaults(bias = FALSE, - method = "rstats") # supply bool and string -*/ -@ - -Note: In \code{cpp}, the default \code{bool} values are \code{true} and -\code{false} whereas in R the valid types are \code{TRUE} or \code{FALSE}. - - -\subsection{Can I use C++11, C++14, C++17, ... with \pkg{Rcpp}?} - -But of course. In a nutshell, this boils down to \emph{what your compiler - supports}, and also \emph{what R supports}. We expanded a little on this in -\href{http://gallery.rcpp.org/articles/rcpp-and-c++11-c++14-c++17/}{Rcpp Gallery - article} providing more detail. What follows in an abridged summary. - -You can always \emph{locally} set appropriate \code{PKG\_CXXFLAGS} as an -environment variable, or via \code{~/.R/Makevars}. You can also plugins and/or R -support from \code{src/Makevars}: - -\begin{itemize} - -\item[\emph{C++11}] has been supported since early 2013 via a plugin selecting - the language standard which is useful for \code{sourceCpp()} etc. For - packages, R has supported it since R 3.1.0 which added the option to select - the language standard via \code{CXX\_STD = CXX11}. As of early 2017, over 120 - packages on CRAN use this. - -\item[\emph{C++14}] has been supported since early 2016 via a plugin selecting - the language standard which is useful for \code{sourceCpp()} etc. For - packages, R supports it since R 3.4.0 adding the option to select the language - standard via \code{CXX\_STD = CXX14}. - -\item[\emph{C++17}] is itself more experimental now, but if you have a compiler - supporting (at least parts of) it, you can use it via plugin (starting with - Rcpp 0.12.10) for use via \code{sourceCpp()}, or via \code{PKG\_CXXFLAGS} or - other means to set compiler options. R support may be available at a later - date. - -\end{itemize} - - -\section{Support} - -\subsection{Is the API documented ?} - -You bet. We use \proglang{doxygen} to generate html, latex and man page -documentation from the source. The html documentation is available for -\href{http://dirk.eddelbuettel.com/code/rcpp/html/index.html}{browsing}, as a -\href{http://dirk.eddelbuettel.com/code/rcpp/Rcpp_refman.pdf}{very large pdf file}, -and all three formats are also available a zip-archives: -\href{http://dirk.eddelbuettel.com/code/rcpp/rcpp-doc-html.zip}{html}, -\href{http://dirk.eddelbuettel.com/code/rcpp/rcpp-doc-latex.zip}{latex}, and -\href{http://dirk.eddelbuettel.com/code/rcpp/rcpp-doc-man.zip}{man}. - -\subsection{Does it really work ?} - -We take quality seriously and have developped an extensive unit test suite to -cover many possible uses of the \pkg{Rcpp} API. - -We are always on the look for more coverage in our testing. Please let us know -if something has not been tested enough. - - -\subsection{Where can I ask further questions ?} - -The -\href{https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel}{Rcpp-devel} -mailing list hosted at R-forge is by far the best place. You may also want -to look at the list archives to see if your question has been asked before. - -You can also use \href{http://stackoverflow.com/questions/tagged/rcpp}{Stack - Overflow via its 'rcpp' tag}. - -\subsection{Where can I read old questions and answers ?} - -The normal \href{https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel}{Rcpp-devel} -mailing list hosting at R-forge contains an archive, which can be -\href{http://lists.r-forge.r-project.org/mailman/swish.cgi?query=listname=rcpp-devel}{searched via swish}. - -Alternatively, one can also use -\href{http://thread.gmane.org/gmane.comp.lang.r.rcpp/}{Gmane on Rcpp-devel} as well as -\href{http://www.mail-archive.com/rcpp-devel@lists.r-forge.r-project.org/info.html}{Mail-Archive - on Rcpp-devel} both of which offer web-based interfaces, including -searching. - -\subsection{I like it. How can I help ?} -\label{helping} - -We maintain a list of -\href{https://github.com/RcppCore/Rcpp/issues?state=open}{open issues in the - Github repository}. We welcome pull requests and suggest that code submissions -come corresponding unit tests and, if applicable, documentation. - -If you are willing to donate time and have skills in C++, let us know. If you are -willing to donate money to sponsor improvements, let us know too. - -You can also spread the word about \pkg{Rcpp}. There are many packages on CRAN -that use \proglang{C++}, yet are not using \pkg{Rcpp}. You could blog about -it, or get the word out otherwise. - -Last but not least the \href{http://gallery.rcpp.org}{Rcpp Gallery} is open -for user contributions. - - -\subsection{I don't like it. How can I help ?} - -It is very generous of you to still want to help. Perhaps you can tell us -what it is that you dislike. We are very open to \emph{constructive} criticism. - -\subsection{Can I have commercial support for \pkg{Rcpp} ?} - -Sure you can. Just send us an email, and we will be happy to discuss the -request. - -\subsection{I want to learn quickly. Do you provide training courses ?} - -Yes. Just send us an email. - -\subsection{Where is the code repository ?} - -From late 2008 to late 2013, we used the -\href{https://r-forge.r-project.org/scm/?group_id=155}{Subversion repository at R-Forge} -which contained \pkg{Rcpp} and a number of related packages. It still has the full -history as well as number of support files. - -We have since switched to a \href{http://github.com/RcppCore/Rcpp}{Git - repository at Github} for \pkg{Rcpp} (as well as for \pkg{RcppArmadillo} and -\pkg{RcppEigen}). - -\section{Known Issues} - -Contained within this section is a list of known issues regarding \pkg{Rcpp}. -The issues listed here are either not able to be fixed due to breaking -application binary interface (ABI), would impact the ability to reproduce -pre-existing results, or require significant work. Generally speaking, these -issues come to light only when pushing the edge capabilities of \pkg{Rcpp}. - -\subsection{\pkg{Rcpp} changed the (const) object I passed by value} - -\pkg{Rcpp} objects are wrappers around the underlying \Rs objects' \code{SEXP}, -or S-expression. The \code{SEXP} is a pointer variable that holds the location -of where the \Rs object data has been stored \citep[][Section 1.1]{R:Internals}. -That is to say, the \code{SEXP} does \textit{not} hold the actual data of the -\Rs object but merely a reference to where the data resides. When creating a new -\pkg{Rcpp} object for an \Rs object to enter \proglang{C++}, this object will -use the same \code{SEXP} that powers the original \Rs object if the types match -otherwise a new \code{SEXP} must be created to be type safe. In essence, the -underlying \code{SEXP} objects are passed by reference without explicit copies -being made into \proglang{C++}. We refer to this arrangement as a -\textit{proxy model}. - -As for the actual implementation, there are a few consequences of the proxy -model. The foremost consequence within this paradigm is that pass by value is -really a pass by reference. In essence, the distinction between the following -two functions is only visual sugar: - -<>= -void implicit_ref(NumericVector X); -void explicit_ref(NumericVector& X); -@ - -In particular, when one is passing by value what occurs is the instantiation of -the new \pkg{Rcpp} object that uses the same \code{SEXP} for the \Rs object. -As a result, the \pkg{Rcpp} object is ``linked'' to the original \Rs object. -Thus, if an operation is performed on the \pkg{Rcpp} object, such as adding 1 -to each element, the operation also updates the \Rs object causing the change to be propagated to \R's interactive environment. - -<>= -#include - -// [[Rcpp::export]] -void implicit_ref(Rcpp::NumericVector X){ - X = X + 1.0; -} - -// [[Rcpp::export]] -void explicit_ref(Rcpp::NumericVector& X){ - X = X + 1.0; -} -@ - -<>= -a <- 1.5:4.5 -b <- 1.5:4.5 -implicit_ref(a) -a -explicit_ref(b) -b -@ - -There are two exceptions to this rule. The first exception is that a deep copy -of the object can be made by explicit use of \code{Rcpp:clone()}. In this case, -the cloned object has no link to the original \Rs object. However, there is a -time cost associated with this procedure as new memory must be allocated and -the previous values must be copied over. The second exception, which was -previously foreshadowed, is encountered when \pkg{Rcpp} and \Rs object types -do not match. One frequent example of this case is when the \Rs object generated -from \code{seq()} or \code{a:b} reports a class of \code{"integer"} while the -\pkg{Rcpp} object is setup to receive the class of \code{"numeric"} as its -object is set to \code{NumericVector} or \code{NumericMatrix}. In such cases, -this would lead to a new \code{SEXP} object being created behind the scenes -and, thus, there would \textit{not} be a link between the \pkg{Rcpp} object -and \Rs object. So, any changes in \proglang{C++} would not be propagated to -\Rs unless otherwise specified. - -<>= -#include - -// [[Rcpp::export]] -void int_vec_type(Rcpp::IntegerVector X){ - X = X + 1.0; -} - -// [[Rcpp::export]] -void num_vec_type(Rcpp::NumericVector X){ - X = X + 1.0; -} -@ - -<>= -a <- 1:5 -b <- 1:5 -class(a) -int_vec_type(a) -a -num_vec_type(b) -b -@ - -With this being said, there is one last area of contention with the proxy model: -the keyword \code{const}. The \code{const} declaration indicates that an object -is not allowed to be modified by any action. Due to the way the proxy -model paradigm works, there is a way to ``override'' the \code{const} designation. -Simply put, one can create a new \pkg{Rcpp} object without the \code{const} -declaration from a pre-existing one. As a result, the new \pkg{Rcpp} object -would be allowed to be modified by the compiler and, thus, modifying the initial -\code{SEXP} object. Therefore, the initially secure \Rs object would be altered. -To illustrate this phenomenon, consider the following scenario: - -<>= -#include - -// [[Rcpp::export]] -Rcpp::NumericVector const_override_ex(const Rcpp::NumericVector& X) { - Rcpp::NumericVector Y(X); // Create object from SEXP - Y = Y * 2; // Modify new object - return X; // Return old object -} -@ - -<>= -x <- 1:10 -const_override_ex(x) -x -@ - -\subsection{Issues with implicit conversion from an \pkg{Rcpp} object to a scalar or -other \pkg{Rcpp} object} - -Not all \pkg{Rcpp} expressions are directly compatible with \code{operator=}. -Compability issues stem from many \pkg{Rcpp} objects and functions returning an -intermediary result which requires an explicit conversion. In such cases, the -user may need to assist the compiler with the conversion. - -There are two ways to assist with the conversion. The first is to construct -storage variable for a result, calculate the result, and then store a value -into it. This is typically what is needed when working with -\code{Character} and \code{String} in \pkg{Rcpp} due to the -\code{Rcpp::internal::string\_proxy} class. Within the following code snippet, -the aforementioned approach is emphasized: - -<>= -#include - -// [[Rcpp::export]] -std::string explicit_string_conv(Rcpp::CharacterVector X) { - std::string s; // define storage - s = X[0]; // assign from CharacterVector - return s; -} -@ - -If one were to use a direct allocation and assignment strategy, -e.g. \code{std::string s = X[0]}, this would result in the compiler triggering -a conversion error on \textit{some} platforms. The error would be similar to: - -<>= -error: no viable conversion from 'Proxy' (aka 'string_proxy<16>') -to 'std::string' (aka 'basic_string, allocator >') -@ - -The second way to help the compiler is to use an explicit \pkg{Rcpp} type conversion -function, if one were to exist. Examples of \pkg{Rcpp} type conversion functions -include \code{as()}, \code{.get()} for \code{cumsum()}, \code{is\_true()} -and \code{is\_false()} for \code{any()} or \code{all()}. - - -\subsection{Using \code{operator=} with a scalar replaced the object instead of -filling element-wise} - -Assignment using the \code{operator=} with either \code{Vector} and -\code{Matrix} classes will not elicit an element-wise fill. If you seek an -element-wise fill, then use the \code{.fill()} member method to propagate a -single value throughout the object. With this being said, the behavior of -\code{operator=} differs for the \code{Vector} and \code{Matrix} classes. - -The implementation of the \code{operator=} for the \code{Vector} class will -replace the existing vector with the assigned value. This behavior is valid -even if the assigned value is a scalar value such as 3.14 or 25 as the object -is cast into the appropriate \pkg{Rcpp} object type. Therefore, if a -\code{Vector} is initialized to have a length of 10 and a scalar is assigned -via \code{operator=}, then the resulting \code{Vector} would have a length of -1. See the following code snippet for the aforementioned behavior. - -<>= -#include - -// [[Rcpp::export]] -void vec_scalar_assign(int n, double fill_val) { - Rcpp::NumericVector X(n); - Rcpp::Rcout << "Value of Vector on Creation: " << std::endl << X << std::endl; - X = fill_val; - Rcpp::Rcout << "Value of Vector after Assignment: " << std::endl << X << std::endl; -} -@ - -<>= -vec_scalar_assign(5L, 3.14) -@ - - -Now, the \code{Matrix} class does not define its own \code{operator=} but -instead uses the \code{Vector} class implementation. This leads to unexpected -results while attempting to use the assignment operator with a scalar. In -particular, the scalar will be coerced into a square \code{Matrix} and then -assigned. For an example of this behavior, consider the following code: - -<>= -#include - -// [[Rcpp::export]] -void mat_scalar_assign(int n, double fill_val) { - Rcpp::NumericMatrix X(n, n); - Rcpp::Rcout << "Value of Matrix on Creation: " << std::endl << X << std::endl; - X = fill_val; - Rcpp::Rcout << "Value of Matrix after Assignment: " << std::endl << X << std::endl; -} -@ - -<>= -mat_scalar_assign(2L, 3.0) -@ - - -\subsection{Long Vector support on Windows} - -Prior to \Rs 3.0.0, the largest vector one could obtain was at most $2^{31} - 1$ -elements. With the release of \Rs 3.0.0, long vector support was added to -allow for largest vector possible to increase up to $2^{52}$ elements on x64 bit -operating systems (c.f. \href{https://stat.ethz.ch/R-manual/R-devel/library/base/html/LongVectors.html}{Long Vectors help entry}). -Once this was established, support for long vectors within the \pkg{Rcpp} paradigm -was introduced with \pkg{Rcpp} version 0.12.0 (c.f \href{http://dirk.eddelbuettel.com/blog/2015/07/25/}{\pkg{Rcpp} 0.12.0 annoucement}). - -However, the requirement for using long vectors in \pkg{Rcpp} necessitates the -presence of compiler support for the \code{R\_xlen\_t}, which is platform -dependent on how \code{ptrdiff\_t} is implemented. Unfortunately, this means -that on the Windows platform the definition of \code{R\_xlen\_t} is of type -\code{long} instead of \code{long long} when compiling under the -\proglang{C++98} specification. Therefore, to solve this issue one must compile -under the specification for \proglang{C++11} or later version. - -There are three options to trigger compilation with \proglang{C++11}. -The first -- and most likely option to use -- will be the plugin support offered -by \pkg{Rcpp} attributes. This is engaged by adding -\code{// [[Rcpp::plugins(cpp11)]]} to the top of the \proglang{C++} script. -For diagnostic and illustrativative purposes, consider the following code -which checks to see if \code{R\_xlen\_t} is available on your platform: - -<>= -#include -// Force compilation mode to C++11 -// [[Rcpp::plugins(cpp11)]] - -// [[Rcpp::export]] -bool test_long_vector_support() { -#ifdef RCPP_HAS_LONG_LONG_TYPES - return true; -#else - return false; -#endif -} -@ - -<>= -test_long_vector_support() -@ - -The remaining two options are for users who have opted to embed \pkg{Rcpp} code -within an \Rs package. In particular, the second option requires adding -\code{CXX\_STD = CXX11} to a \code{Makevars} file found in the \code{/src} -directory. Finally, the third option is to add \code{SystemRequirements:C++11} -in the package's \code{DESCRIPTION} file. - -Please note that the support for \proglang{C++11} prior to \Rs v3.3.0 on Windows -is limited. Therefore, plan accordingly if the goal is to support older -versions of \R. - -\subsection{Sorting with STL on a \code{CharacterVector} produces problematic -results} - -The Standard Template Library's (STL) \code{std::sort} algorithm performs -adequately for the majority of \pkg{Rcpp} data types. The notable exception -that makes what would otherwise be a universal quantifier into an existential -quantifier is the \code{CharacterVector} data type. Chiefly, the issue with -sorting strings is related to how the \code{CharacterVector} relies upon the -use of \code{Rcpp::internal::string\_proxy}. In particular, -\code{Rcpp::internal::string\_proxy} is \textit{not} MoveAssignable since the -left hand side of \code{operator=(const string\_proxy \&rhs)} is \textit{not} -viewed as equivalent to the right hand side before the operation -\citep[][p. 466, Table 22]{Cpp11}. This further complicates matters when -using \code{CharacterVector} with \code{std::swap}, \code{std::move}, -\code{std::copy} and their variants. - -To avoid unwarranted pain with sorting, the preferred approach is to use the -\code{.sort()} member function of \pkg{Rcpp} objects. The member function -correctly applies the sorting procedure to \pkg{Rcpp} objects regardless of -type. Though, sorting is slightly problematic due to locale as explained in the -next entry. In the interim, the following code example illustrates the preferred -approach alongside the problematic STL approach: - -<>= -#include - -// [[Rcpp::export]] -Rcpp::CharacterVector preferred_sort(Rcpp::CharacterVector x) { - Rcpp::CharacterVector y = Rcpp::clone(x); - y.sort(); - return y; -} - -// [[Rcpp::export]] -Rcpp::CharacterVector stl_sort(Rcpp::CharacterVector x) { - Rcpp::CharacterVector y = Rcpp::clone(x); - std::sort(y.begin(), y.end()); - return y; -} -@ - -<>= -set.seed(123) -(X <- sample(c(LETTERS[1:5], letters[1:6]), 11)) -preferred_sort(X) -stl_sort(X) -@ - -In closing, the results of using the STL approach do change depending on -whether \code{libc++} or \code{libstdc++} standard library is used to compile -the code. When debugging, this does make the issue particularly complex to -sort out. Principally, compilation with \code{libc++} and STL has been shown -to yield the correct results. However, it is not wise to rely upon this library -as a majority of code is compiled against \code{libstdc++} as it more complete. - -\subsection{Lexicographic order of string sorting differs due to capitalization} - -Comparing strings within \Rs hinges on the ability to process the locale or -native-language environment of the string. In \R, there is a function called -\code{Scollate} that performs the comparison on locale. Unfortunately, this -function has not been made publicly available and, thus, \pkg{Rcpp} does -\textit{not} have access to it within its implementation of \code{StrCmp}. -As a result, strings that are sorted under the \code{.sort()} member function -are ordered improperly. Specifically, if capitalization is present, then -capitalized words are sorted together followed by the sorting of lowercase -words instead of a mixture of capitalized and lowercase words. The issue is -illustrated by the following code example: - -<>= -#include - -// [[Rcpp::export]] -Rcpp::CharacterVector rcpp_sort(Rcpp::CharacterVector X) { - X.sort(); - return X; -} -@ - -<>= -x <- c("B", "b", "c", "A", "a") -sort(x) -rcpp_sort(x) -@ - - -\bibliographystyle{plainnat} -\bibliography{\Sexpr{Rcpp:::bib()}} -\end{document} - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-FAQ.pdf b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-FAQ.pdf deleted file mode 100644 index 166cd80..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-FAQ.pdf and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-attributes.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-attributes.R deleted file mode 100644 index 2b180b9..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-attributes.R +++ /dev/null @@ -1,72 +0,0 @@ -### R code from vignette source 'Rcpp-attributes.Rnw' - -################################################### -### code chunk number 1: Rcpp-attributes.Rnw:41-43 -################################################### -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") - - -################################################### -### code chunk number 3: Rcpp-attributes.Rnw:149-151 (eval = FALSE) -################################################### -## sourceCpp("convolve.cpp") -## convolveCpp(x, y) - - -################################################### -### code chunk number 5: Rcpp-attributes.Rnw:179-180 (eval = FALSE) -################################################### -## function(file, colNames=character(), comment="#", header=TRUE) - - -################################################### -### code chunk number 19: Rcpp-attributes.Rnw:518-528 (eval = FALSE) -################################################### -## cppFunction(' -## int fibonacci(const int x) { -## if (x < 2) -## return x; -## else -## return (fibonacci(x - 1)) + fibonacci(x - 2); -## } -## ') -## -## evalCpp('std::numeric_limits::max()') - - -################################################### -### code chunk number 20: Rcpp-attributes.Rnw:533-534 (eval = FALSE) -################################################### -## cppFunction(depends = 'RcppArmadillo', code = '...') - - -################################################### -### code chunk number 21: Rcpp-attributes.Rnw:565-566 (eval = FALSE) -################################################### -## Rcpp.package.skeleton("NewPackage", attributes = TRUE) - - -################################################### -### code chunk number 22: Rcpp-attributes.Rnw:572-574 (eval = FALSE) -################################################### -## Rcpp.package.skeleton("NewPackage", example_code = FALSE, -## cpp_files = c("convolve.cpp")) - - -################################################### -### code chunk number 26: Rcpp-attributes.Rnw:626-627 (eval = FALSE) -################################################### -## compileAttributes() - - -################################################### -### code chunk number 30: Rcpp-attributes.Rnw:715-720 (eval = FALSE) -################################################### -## #' The length of a string (in characters). -## #' -## #' @param str input character vector -## #' @return characters in each element of the vector -## strLength <- function(str) - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-attributes.Rnw b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-attributes.Rnw deleted file mode 100644 index fafc5f3..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-attributes.Rnw +++ /dev/null @@ -1,829 +0,0 @@ -% !Rnw driver = highlight::HighlightWeaveLatex() -\documentclass[11pt]{article} -%\VignetteIndexEntry{Rcpp-attributes} -%\VignetteEngine{highlight::highlight} -%\VignetteKeywords{Rcpp, attributes} -%\VignetteDepends{Rcpp} - -\usepackage[USletter]{vmargin} -\setmargrb{1.25in}{1.25in}{1.25in}{1.25in} - - -\usepackage{textcomp} -\usepackage{color, alltt} -\usepackage[authoryear,round,longnamesfirst]{natbib} -\usepackage[colorlinks]{hyperref} -\definecolor{link}{rgb}{0,0,0.3} %% next few lines courtesy of RJournal.sty -\hypersetup{ - colorlinks,% - citecolor=link,% - filecolor=link,% - linkcolor=link,% - urlcolor=link -} - -\usepackage{microtype} %% cf http://www.khirevich.com/latex/microtype/ -\usepackage[T1]{fontenc} %% cf http://www.khirevich.com/latex/font/ -\usepackage[bitstream-charter]{mathdesign} %% cf http://www.khirevich.com/latex/font/ - -\newcommand{\proglang}[1]{\textsf{#1}} -\newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}} -\newcommand{\code}[1]{\texttt{#1}} - -%% This corresponds to setting boxes=TRUE for highlight -\newsavebox{\hlbox} -\definecolor{hlBg}{rgb}{0.949019607843137,0.949019607843137,0.949019607843137} -\definecolor{hlBd}{rgb}{0.9,0.9,0.9} % border -\renewenvironment{Hchunk}{\vspace{0.5em}\noindent\begin{lrbox}{\hlbox}\begin{minipage}[b]{.98\linewidth}}% - {\end{minipage}\end{lrbox}\fcolorbox{hlBd}{hlBg}{\usebox{\hlbox}}\vspace{0.5em}} - - -<>= -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -@ - -\author{J.J. Allaire \and Dirk Eddelbuettel \and Romain Fran\c{c}ois} -\title{\pkg{Rcpp} Attributes} -\date{\pkg{Rcpp} version \Sexpr{prettyVersion} as of \Sexpr{prettyDate}} - -\begin{document} -\maketitle - -\abstract{ - \noindent - \textsl{Rcpp attributes} provide a high-level syntax for declaring \proglang{C++} - functions as callable from \proglang{R} and automatically generating the code - required to invoke them. Attributes are intended to facilitate both interactive use - of \proglang{C++} within \proglang{R} sessions as well as to support \proglang{R} - package development. The implementation of attributes is based on previous - work in the \pkg{inline} package \citep{CRAN:inline}. -} - - -\section{Introduction} - -Attributes are a new feature of \pkg{Rcpp} version 0.10.0 \citep{CRAN:Rcpp,JSS:Rcpp} -that provide infrastructure for seamless language bindings between \proglang{R} and -\proglang{C++}. The motivation for attributes is several-fold: - -\begin{enumerate} -\item - Reduce the learning curve associated with using C++ and R together -\item - Eliminate boilerplate conversion and marshaling code wherever - possible -\item - Seamless use of C++ within interactive R sessions -\item - Unified syntax for interactive work and package development -\end{enumerate} - -The core concept is to add annotations to \proglang{C++} source -files that provide the context required to automatically generate \proglang{R} -bindings to \proglang{C++} functions. Attributes and their supporting -functions include: - -\begin{itemize} -\item - \texttt{Rcpp::export} attribute to export a \proglang{C++} function - to \proglang{R} -\item - \texttt{sourceCpp} function to source exported functions from a file -\item - \texttt{cppFunction} and \texttt{evalCpp} functions for inline - declarations and execution -\item - \texttt{Rcpp::depends} attribute for specifying additional build - dependencies for \texttt{sourceCpp} -\end{itemize} - -Attributes can also be used for package development via the -\texttt{compileAttributes} function, which automatically generates -\texttt{extern "C"} and \texttt{.Call} wrappers for \proglang{C++} -functions within packages. - -\section{Using Attributes} - -Attributes are annotations that are added to C++ source files to provide -additional information to the compiler. \pkg{Rcpp} supports attributes -to indicate that C++ functions should be made available as R functions, -as well as to optionally specify additional build dependencies for source files. - -\proglang{C++11} specifies a standard syntax for attributes -\citep{Maurer+Wong:2008:AttributesInC++}. Since this standard isn't yet -fully supported across all compilers, \pkg{Rcpp} attributes are included in -source files using specially formatted comments. - -\subsection{Exporting C++ Functions} - -The \texttt{sourceCpp} function parses a \proglang{C++} file and looks for -functions marked with the \texttt{Rcpp::export} attribute. A shared -library is then built and its exported functions are made available as R -functions in the specified environment. For example, this source file -contains an implementation of convolve (note the \texttt{Rcpp::export} -attribute in the comment above the function): - -<>= -#include -using namespace Rcpp; - -// [[Rcpp::export]] -NumericVector convolveCpp(NumericVector a, NumericVector b) { - - int na = a.size(), nb = b.size(); - int nab = na + nb - 1; - NumericVector xab(nab); - - for (int i = 0; i < na; i++) - for (int j = 0; j < nb; j++) - xab[i + j] += a[i] * b[j]; - - return xab; -} -@ - -The addition of the export attribute allows us to do this from the \proglang{R} -prompt: - -<>= -sourceCpp("convolve.cpp") -convolveCpp(x, y) -@ - -We can now write \proglang{C++} functions using built-in \proglang{C++} types -and \pkg{Rcpp} wrapper types and then source them just as we would an -\proglang{R} script. - -The \texttt{sourceCpp} function performs caching based on the last -modified date of the source file and it's local dependencies so as -long as the source does not change the compilation will occur only -once per R session. - -\subsection{Specifying Argument Defaults} - -If default argument values are provided in the C++ function definition -then these defaults are also used for the exported R function. For example, -the following C++ function: - -<>= -DataFrame readData( - CharacterVector file, - CharacterVector colNames = CharacterVector::create(), - std::string comment = "#", - bool header = true) -@ - -Will be exported to R as: - -<>= -function(file, colNames=character(), comment="#", header=TRUE) -@ - -Note that C++ rules for default arguments still apply: they must occur -consecutively at the end of the function signature and (unlike R) can't rely -on the values of other arguments. - -Not all \proglang{C++} default argument values can be parsed into their -\proglang{R} equivalents, however the most common cases are supported, including: - -\begin{itemize} -\item - String literals delimited by quotes (e.g. \texttt{"foo"}) -\item - Decimal numeric values (e.g. \texttt{10} or \texttt{4.5}) -\item - Pre-defined constants including \texttt{true}, \texttt{false}, - \texttt{R\_NilValue}, \texttt{NA\_STRING}, \texttt{NA\_INTEGER}, - \texttt{NA\_REAL}, and \texttt{NA\_LOGICAL}. -\item - Selected vector types (\texttt{CharacterVector}, \texttt{IntegerVector}, - and \texttt{NumericVector}) instantiated using the \texttt{::create} - static member function. -\item - \texttt{Matrix} types instantiated using the \texttt{rows}, - \texttt{cols} constructor. -\end{itemize} - -\subsection{Signaling Errors} - -Within \proglang{R} code the \texttt{stop} function is typically used to signal -errors. Within \proglang{R} extensions written in \proglang{C} the \texttt{Rf\_error} function is typically used. However, within \proglang{C++} code you cannot -safely use \texttt{Rf\_error} because it results in a \texttt{longjmp} over -any \proglang{C++} destructors on the stack. - -The correct way to signal errors within \proglang{C++} functions is to throw an \\\texttt{Rcpp::exception}. For example: - -<>= -if (unexpectedCondition) - throw Rcpp::exception("Unexpected condition occurred"); -@ - -There is also an \texttt{Rcpp::stop} function that is shorthand for throwing -an \\\texttt{Rcpp::exception}. For example: - -<>= -if (unexpectedCondition) - Rcpp::stop("Unexpected condition occurred"); -@ - -In both cases the \proglang{C++} exception will be caught by \pkg{Rcpp} -prior to returning control to \proglang{R} and converted into the correct -signal to \proglang{R} that execution should stop with the specified message. - -You can similarly also signal warnings with the \texttt{Rcpp::warning} -function: - -<>= -if (unexpectedCondition) - Rcpp::warning("Unexpected condition occurred"); -@ - -\subsection{Supporting User Interruption} - -If your function may run for an extended period of time, users will appreciate -the ability to interrupt it's processing and return to the REPL. This is -handled automatically for R code (as R checks for user interrupts periodically -during processing) however requires explicit accounting for in C and C++ -extensions to R. To make computations interrupt-able, you should periodically -call the \texttt{Rcpp::checkUserInterrupt} function, for example: - -<>= -for (int i=0; i<1000000; i++) { - - // check for interrupt every 1000 iterations - if (i % 1000 == 0) - Rcpp::checkUserInterrupt(); - - // ...do some expensive work... - -} -@ - -A good guideline is to call \texttt{Rcpp::checkUserInterrupt} every 1 or 2 -seconds that your computation is running. In the above code, if the user -requests an interrupt then an exception is thrown and the attributes wrapper -code arranges for the user to be returned to the REPL. - -Note that R provides a \proglang{C} API for the same purpose -(\texttt{R\_CheckUserInterrupt}) however this API is not safe to use in -\proglang{C++} code as it uses \texttt{longjmp} to exit the current scope, -bypassing any C++ destructors on the stack. The \texttt{Rcpp::checkUserInterrupt} -function is provided as a safe alternative for \proglang{C++} code. - -\subsection{Embedding R Code} - -Typically \proglang{C++} and \proglang{R} code are kept in their own source -files. However, it's often convenient to bundle code from both languages into -a common source file that can be executed using single call to \texttt{sourceCpp}. - -To embed chunks of \proglang{R} code within a \proglang{C++} -source file you include the \proglang{R} code within a block comment that -has the prefix of \texttt{/*** R}. For example: - -<>= -/*** R - -# Call the fibonacci function defined in C++ -fibonacci(10) - -*/ -@ - -Multiple \proglang{R} code chunks can be included in a \proglang{C++} file. The -\texttt{sourceCpp} function will first compile the \proglang{C++} code into a -shared library and then source the embedded \proglang{R} code. - -\subsection{Modifying Function Names} - -You can change the name of an exported function as it appears to \proglang{R} by -adding a name parameter to \texttt{Rcpp::export}. For example: - -<>= -// [[Rcpp::export(name = ".convolveCpp")]] -NumericVector convolveCpp(NumericVector a, NumericVector b) -@ - -Note that in this case since the specified name is prefaced by a \code{.} the -exported R function will be hidden. You can also use this method to provide -implementations of S3 methods (which wouldn't otherwise be possible because -C++ functions can't contain a '.' in their name). - -\subsection{Function Requirements} - -Functions marked with the \texttt{Rcpp::export} attribute must meet several -requirements to be correctly handled: - -\begin{itemize} -\item - Be defined in the global namespace (i.e. not within a C++ namespace declaration) -\item - Have a return type that is either void or compatible with \texttt{Rcpp::wrap} - and parameter types that are compatible with \texttt{Rcpp::as} (see sections - 3.1 and 3.2 of the `\textsl{Rcpp-introduction}' vignette for more details). - \item - Use fully qualified type names for the return value and all parameters. - Rcpp types may however appear without a namespace qualifier (i.e. - \texttt{DataFrame} is okay as a type name but \texttt{std::string} must be - specified fully). -\end{itemize} - -\subsection{Random Number Generation} - -\proglang{R} functions implemented in \proglang{C} or \proglang{C++} need -to be careful to surround use of internal random number generation routines -(e.g. \texttt{unif\_rand}) with calls to \texttt{GetRNGstate} and -\texttt{PutRNGstate}. - -Within \pkg{Rcpp}, this is typically done using the \texttt{RNGScope} class. -However, this is not necessary for \proglang{C++} functions exported using -attributes because an \texttt{RNGScope} is established for them automatically. -Note that \pkg{Rcpp} implements \texttt{RNGScope} using a counter, so it's -still safe to execute code that may establish it's own \texttt{RNGScope} (such -as the \pkg{Rcpp} sugar functions that deal with random number generation). - -The overhead associated with using \texttt{RNGScope} is negligible (only a -couple of milliseconds) and it provides a guarantee that all C++ code -will inter-operate correctly with R's random number generation. If you are -certain that no C++ code will make use of random number generation and the -2ms of execution time is meaningful in your context, you can disable the -automatic injection of \texttt{RNGScope} using the \texttt{rng} parameter -of the \texttt{Rcpp::export} attribute. For example: - -<>= -// [[Rcpp::export(rng = false)]] -double myFunction(double input) { - // ...code that never uses R random number generation... -} -@ - -\subsection{Importing Dependencies} - -It's also possible to use the \texttt{Rcpp::depends} attribute to declare -dependencies on other packages. For example: - -<>= -// [[Rcpp::depends(RcppArmadillo)]] - -#include -using namespace Rcpp; - -// [[Rcpp::export]] -List fastLm(NumericVector yr, NumericMatrix Xr) { - - int n = Xr.nrow(), k = Xr.ncol(); - - arma::mat X(Xr.begin(), n, k, false); - arma::colvec y(yr.begin(), yr.size(), false); - - arma::colvec coef = arma::solve(X, y); - arma::colvec resid = y - X*coef; - - double sig2 = arma::as_scalar(arma::trans(resid)*resid/(n-k)); - arma::colvec stderrest = arma::sqrt( - sig2 * arma::diagvec( arma::inv(arma::trans(X)*X)) ); - - return List::create(Named("coefficients") = coef, - Named("stderr") = stderrest); -} -@ - -The inclusion of the \texttt{Rcpp::depends} attribute causes \texttt{sourceCpp} -to configure the build environment to correctly compile and link against the -\pkg{RcppArmadillo} package. Source files can declare more than one dependency -either by using multiple \texttt{Rcpp::depends} attributes or with syntax like this: - -<>= -// [[Rcpp::depends(Matrix, RcppArmadillo)]] -@ - -Dependencies are discovered both by scanning for package include directories -and by invoking \pkg{inline} plugins if they are available for a package. - -Note that while the \texttt{Rcpp::depends} attribute establishes dependencies -for \texttt{sourceCpp}, it's important to note that if you include the same -source file in an \proglang{R} package these dependencies must still be -listed in the \texttt{Imports} and/or \texttt{LinkingTo} fields of the package -\texttt{DESCRIPTION} file. - -\subsection{Sharing Code} - -The core use case for \texttt{sourceCpp} is the compilation of a single -self-contained source file. Code within this file can import other C++ code -by using the \texttt{Rcpp::depends} attribute as described above. - -The recommended practice for sharing C++ code across many uses of -\texttt{sourceCpp} is therefore to create an R package to wrap the C++ -code. This has many benefits not the least of which is easy distribution of -shared code. More information on creating packages that contain C++ code -is included in the Package Development section below. - -\subsubsection{Shared Code in Header Files} - -If you need to share a small amount of C++ code between source files -compiled with \texttt{sourceCpp} and the option of creating a package -isn't practical, then you can also share code using local includes of C++ -header files. To do this, create a header file with the definition of -shared functions, classes, enums, etc. For example: - -<>= -#ifndef __UTILITIES__ -#define __UTILITIES__ - -inline double timesTwo(double x) { - return x * 2; -} - -#endif // __UTILITIES__ -@ - -Note the use of the \texttt{\#ifndef} include guard, this is import to ensure -that code is not included more than once in a source file. You should -use an include guard and be sure to pick a unique name for the corresponding -\texttt{\#define}. - -Also note the use of the \code{inline} keyword preceding the function. This -is important to ensure that there are not multiple definitions of -functions included from header files. Classes fully defined in header files -automatically have inline semantics so don't require this treatment. - -To use this code in a source file you'd just include -it based on it's relative path (being sure to use \texttt{"} as the -delimiter to indicate a local file reference). For example: - -<>= -#include "shared/utilities.hpp" - -// [[Rcpp::export]] -double transformValue(double x) { - return timesTwo(x) * 10; -} -@ - -\subsubsection{Shared Code in C++ Files} - -When scanning for locally included header files \code{sourceCpp} also checks -for a corresponding implementation file and automatically includes it in the -compilation if it exists. - -This enables you to break the shared code entirely into it's own source file. -In terms of the above example, this would mean having only a function -declaration in the header: - -<>= -#ifndef __UTILITIES__ -#define __UTILITIES__ - -double timesTwo(double x); - -#endif // __UTILITIES__ -@ - -Then actually defining the function in a separate source file with the -same base name as the header file but with a .cpp extension (in the above -example this would be \code{utilities.cpp}): - -<>= -#include "utilities.hpp" - -double timesTwo(double x) { - return x * 2; -} -@ - -It's also possible to use attributes to declare dependencies and exported -functions within shared header and source files. This enables you to take -a source file that is typically used standalone and include it when compiling -another source file. - -Note that since additional source files are processed as separate translation -units the total compilation time will increase proportional to the number of -files processed. From this standpoint it's often preferable to use shared -header files with definitions fully inlined as demonstrated above. - -Note also that embedded R code is only executed for the main source file not -those referenced by local includes. - -\subsection{Including C++ Inline} - -Maintaining C++ code in it's own source file provides several benefits including -the ability to use \proglang{C++} aware text-editing tools and straightforward -mapping of compilation errors to lines in the source file. However, it's also -possible to do inline declaration and execution of C++ code. - -There are several ways to accomplish this, including passing a code -string to \texttt{sourceCpp} or using the shorter-form \texttt{cppFunction} -or \texttt{evalCpp} functions. For example: - -<>= -cppFunction(' - int fibonacci(const int x) { - if (x < 2) - return x; - else - return (fibonacci(x - 1)) + fibonacci(x - 2); - } -') - -evalCpp('std::numeric_limits::max()') -@ - -You can also specify a depends parameter to \texttt{cppFunction} or \texttt{evalCpp}: - -<>= -cppFunction(depends = 'RcppArmadillo', code = '...') -@ - -\section{Package Development} - -One of the goals of \pkg{Rcpp} attributes is to simultaneously facilitate -ad-hoc and interactive work with \proglang{C++} while also making it very easy to -migrate that work into an \proglang{R} package. There are several benefits of -moving code from a standalone \proglang{C++} source file to a package: - -\begin{enumerate} -\item - Your code can be made available to users without \proglang{C++} development - tools (at least on Windows or Mac OS X where binary packages are common) -\item - Multiple source files and their dependencies are handled automatically - by the \proglang{R} package build system -\item - Packages provide additional infrastructure for testing, documentation - and consistency -\end{enumerate} - -\subsection{Package Creation} - -To create a package that is based on \pkg{Rcpp} you should follow the -guidelines in the `\textsl{Rcpp-package}' vignette. For a new package this -is most conveniently done using the \texttt{Rcpp.package.skeleton} function. - -To generate a new package with a simple hello, world function that uses -attributes you can do the following: - -<>= -Rcpp.package.skeleton("NewPackage", attributes = TRUE) -@ - -To generate a package based on \proglang{C++} files that you've been using -with \texttt{sourceCpp} you can use the \texttt{cpp\_files} parameter: - -<>= -Rcpp.package.skeleton("NewPackage", example_code = FALSE, - cpp_files = c("convolve.cpp")) -@ - -\subsection{Specifying Dependencies} - -Once you've migrated \proglang{C++} code into a package, the dependencies for -source files are derived from the \texttt{Imports} and \texttt{LinkingTo} fields -in the package \texttt{DESCRIPTION} file rather than the \texttt{Rcpp::depends} -attribute. Some packages also require the addition of an entry to the package -\texttt{NAMESPACE} file to ensure that the package's shared library is loaded -prior to callers using the package. For every package you import C++ code from -(including \pkg{Rcpp}) you need to add these entries. - -Packages that provide only C++ header files (and no shared library) need only -be referred to using \texttt{LinkingTo}. You should consult the documentation -for the package you are using for the requirements particular to that package. - -For example, if your package depends on \pkg{Rcpp} you'd have the following -entries in the \texttt{DESCRIPTION} file: - -<>= -Imports: Rcpp (>= 0.11.4) -LinkingTo: Rcpp -@ - -And the following entry in your \texttt{NAMESPACE} file: - -<>= -importFrom(Rcpp, evalCpp) -@ - -If your package additionally depended on the \pkg{BH} (Boost headers) package -you'd just add an entry for \pkg{BH} to the \texttt{LinkingTo} field since -\pkg{BH} is a header-only package: - -<>= -Imports: Rcpp (>= 0.11.4) -LinkingTo: Rcpp, BH -@ - - -\subsection{Exporting R Functions} - -Within interactive sessions you call the \texttt{sourceCpp} function -on individual files to export \proglang{C++} functions into the global -environment. However, for packages you call a single utility function to -export all \proglang{C++} functions within the package. - -The \texttt{compileAttributes} function scans the source files within a package -for export attributes and generates code as required. For example, executing -this from within the package working directory: - -<>= -compileAttributes() -@ - -Results in the generation of the following two source files: - -\begin{itemize} -\item - \texttt{src/RcppExports.cpp} -- The \texttt{extern "C"} wrappers required - to call exported \proglang{C++} functions within the package. -\item - \texttt{R/RcppExports.R} -- The \texttt{.Call} wrappers required to call - the \texttt{extern "C"} functions defined in \texttt{RcppExports.cpp}. -\end{itemize} - -You should re-run \texttt{compileAttributes} whenever functions are added, -removed, or have their signatures changed. Note that if you are using either -RStudio or \pkg{devtools} to build your package then the -\texttt{compileAttributes} function is called automatically whenever your -package is built. - -The \texttt{compileAttributes} function deals only with exporting -\proglang{C++} functions to \proglang{R}. If you want the functions to -additionally be publicly available from your package's namespace another -step may be required. Specifically, if your package \texttt{NAMESPACE} file -does not use a pattern to export functions then you should add an explicit -entry to \texttt{NAMESPACE} for each R function you want publicly available. - -\subsection{Types in Generated Code} - -In some cases the signatures of the C++ functions that are generated within -\texttt{RcppExports.cpp} may have additional type requirements beyond the core -standard library and \pkg{Rcpp} types (e.g. \texttt{CharacterVector}, -\texttt{NumericVector}, etc.). Examples might include convenience typedefs, -as/wrap handlers for marshaling between custom types and SEXP, or types -wrapped by the Rcpp \texttt{XPtr} template. - -In this case, you can create a header file that contains these type definitions -(either defined inline or by including other headers) and have this header -file automatically included in \texttt{RcppExports.cpp}. Headers named with -the convention \texttt{pkgname\_types} are automatically included along with -the generated C++ code. For example, if your package is named \pkg{fastcode} -then any of the following header files would be automatically included in -\texttt{RcppExports.cpp}: - -<>= -src/fastcode_types.h -src/fastcode_types.hpp -inst/include/fastcode_types.h -inst/include/fastcode_types.hpp -@ - -There is one other mechanism for type visibility in \texttt{RcppExports.cpp}. -If your package provides a master include file for consumption by C++ clients -then this file will also be automatically included. For example, if the -\pkg{fastcode} package had a C++ API and the following header file: - -<>= -inst/include/fastcode.h -@ - -This header file will also automatically be included in -\texttt{RcppExports.cpp}. Note that the convention of using \texttt{.h} for -header files containing C++ code may seem unnatural, but this comes from the -recommended practices described in `\textsl{Writing R Extensions}' -\citep{R:Extensions}. - -\subsection{Roxygen Comments} - -The \pkg{roxygen2} package \citep{CRAN:roxygen2} provides a facility for -automatically generating \proglang{R} documentation files based on specially -formatted comments in \proglang{R} source code. - -If you include roxygen comments in your \proglang{C++} source file with a -\texttt{//\textquotesingle} prefix then \texttt{compileAttributes} will transpose them -into R roxygen comments within \texttt{R/RcppExports.R}. For example the -following code in a \proglang{C++} source file: - -<>= -//' The length of a string (in characters). -//' -//' @param str input character vector -//' @return characters in each element of the vector -// [[Rcpp::export]] -NumericVector strLength(CharacterVector str) -@ - -Results in the following code in the generated \proglang{R} source file: - -<>= -#' The length of a string (in characters). -#' -#' @param str input character vector -#' @return characters in each element of the vector -strLength <- function(str) -@ - -\subsection{Providing a C++ Interface} - -The interface exposed from \proglang{R} packages is most typically a set of -\proglang{R} functions. However, the \proglang{R} package system also provides -a mechanism to allow the exporting of \proglang{C} and \proglang{C++} -interfaces using package header files. This is based on the -\texttt{R\_RegisterCCallable} and \texttt{R\_GetCCallable} functions described in -`\textsl{Writing R Extensions}' \citep{R:Extensions}. - -\proglang{C++} interfaces to a package are published within the -top level \texttt{include} directory of the package (which within the package -source directory is located at \texttt{inst/include}). The \proglang{R} build -system automatically adds the required \texttt{include} directories for all -packages specified in the \texttt{LinkingTo} field of the package -\texttt{DESCRIPTION} file. - -\subsubsection{Interfaces Attribute} - -The \texttt{Rcpp::interfaces} attribute can be used to automatically -generate a header-only interface to your \proglang{C++} functions -within the \texttt{include} directory of your package. - -The \texttt{Rcpp::interfaces} attribute is specified on a per-source -file basis, and indicates which interfaces (\proglang{R}, \proglang{C++}, -or both) should be provided for exported functions within the file. - -For example, the following specifies that both R and \proglang{C++} interfaces -should be generated for a source file: - -<>= -// [[Rcpp::interfaces(r, cpp)]] -@ - -Note that the default behavior if an \texttt{Rcpp::interfaces} attribute -is not included in a source file is to generate an R interface only. - -\subsubsection{Generated Code} - -If you request a \texttt{cpp} interface for a source file then -\texttt{compileAttributes} generates the following header files -(substituting \emph{Package} with the name of the package code is being -generated for): - -<>= -inst/include/Package.h -inst/include/Package_RcppExports.h -@ - -The \texttt{Package\_RcppExports.h} file has inline definitions for all -exported \proglang{C++} functions that enable calling them using the -\texttt{R\_GetCCallable} mechanism. - -The \texttt{Package.h} file does nothing other than include the -\texttt{Package\_RcppExports.h} header. This is done so -that package authors can replace the \texttt{Package.h} header with -a custom one and still be able to include the automatically generated exports -(details on doing this are provided in the next section). - -The exported functions are defined within a \proglang{C++} namespace that matches -the name of the package. For example, an exported \proglang{C++} function -\texttt{bar} could be called from package \texttt{MyPackage} as follows: - -<>= -// [[Rcpp::depends(MyPackage)]] - -#include - -void foo() { - MyPackage::bar(); -} -@ - -\subsubsection{Including Additional Code} - -You might wish to use the \texttt{Rcpp::interfaces} attribute to generate -a part of your package's \proglang{C++} interface but also provide -additional custom \proglang{C++} code. In this case you -should replace the generated \texttt{Package.h} file with one of your own. - -Note that the way \pkg{Rcpp} distinguishes user verses generated files is by checking -for the presence a special token in the file (if it's present then it's known -to be generated and thus safe to overwrite). You'll see this token at the top -of the generated \texttt{Package.h} file, be sure to remove it if you want -to provide a custom header. - -Once you've established a custom package header file, you need only include the -\texttt{Package\_RcppExports.h} file within your header to make available -the automatically generated code alongside your own. - -If you need to include code from your custom header files within the -compilation of your package source files, you will also need to add the -following entry to \texttt{Makevars} and \texttt{Makevars.win} (both are -in the \texttt{src} directory of your package): - -<>= -PKG_CPPFLAGS += -I../inst/include/ -@ - -Note that the R package build system does not automatically force a rebuild -when headers in \texttt{inst/include} change, so you should be sure to perform a -full rebuild of the package after making changes to these headers. - -\bibliographystyle{plainnat} -\bibliography{\Sexpr{Rcpp:::bib()}} - -\end{document} - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-attributes.pdf b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-attributes.pdf deleted file mode 100644 index 25c79e4..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-attributes.pdf and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-extending.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-extending.R deleted file mode 100644 index f936873..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-extending.R +++ /dev/null @@ -1,57 +0,0 @@ -### R code from vignette source 'Rcpp-extending.Rnw' - -################################################### -### code chunk number 1: Rcpp-extending.Rnw:45-50 -################################################### -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -require(inline) -require(highlight) -require(Rcpp) - - -################################################### -### code chunk number 3: Rcpp-extending.Rnw:92-112 -################################################### -code <- ' -#include -using namespace Rcpp; - -// [[Rcpp::export]] -List fx(List input){ // we get a list from R - -// pull std::vector from R list -// this is achieved through an implicit call to Rcpp::as -std::vector x = input["x"] ; - -// return an R list -// this is achieved through implicit call to Rcpp::wrap -return List::create( - _["front"] = x.front(), - _["back"] = x.back() - ); -} -' -writeLines( code, "code.cpp" ) - - -################################################### -### code chunk number 4: Rcpp-extending.Rnw:114-115 -################################################### -external_highlight( "code.cpp", type = "LATEX", doc = FALSE ) - - -################################################### -### code chunk number 5: Rcpp-extending.Rnw:118-121 -################################################### -Rcpp::sourceCpp(file= "code.cpp") -input <- list( x = seq(1, 10, by = 0.5) ) -fx( input ) - - -################################################### -### code chunk number 15: Rcpp-extending.Rnw:357-358 -################################################### -unlink( "code.cpp" ) - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-extending.Rnw b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-extending.Rnw deleted file mode 100644 index 568f7fb..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-extending.Rnw +++ /dev/null @@ -1,373 +0,0 @@ -% !Rnw driver = highlight::HighlightWeaveLatex() -\documentclass[10pt]{article} -%\VignetteIndexEntry{Rcpp-extending} -%\VignetteEngine{highlight::highlight} -%\VignetteKeywords{Rcpp, package} -%\VignetteDepends{Rcpp} - -\usepackage[USletter]{vmargin} -\setmargrb{0.75in}{0.75in}{0.75in}{0.75in} - -\usepackage{color, alltt} -\usepackage[authoryear,round,longnamesfirst]{natbib} -\usepackage[colorlinks]{hyperref} -\definecolor{link}{rgb}{0,0,0.3} %% next few lines courtesy of RJournal.sty -\hypersetup{ - colorlinks,% - citecolor=link,% - filecolor=link,% - linkcolor=link,% - urlcolor=link -} - -\usepackage{microtype} %% cf http://www.khirevich.com/latex/microtype/ -\usepackage[T1]{fontenc} %% cf http://www.khirevich.com/latex/font/ -\usepackage[bitstream-charter]{mathdesign} %% cf http://www.khirevich.com/latex/font/ - -\newcommand{\proglang}[1]{\textsf{#1}} -\newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}} - -%% defined as a stop-gap measure til interaction with highlight is sorted out -\newcommand{\hlboxlessthan}{ \hlnormalsizeboxlessthan} -\newcommand{\hlboxgreaterthan}{\hlnormalsizeboxgreaterthan} -\newcommand{\hlboxopenbrace}{ \hlnormalsizeboxopenbrace} -\newcommand{\hlboxclosebrace}{ \hlnormalsizeboxclosebrace} -\newcommand{\hlboxbacktick}{ \hlnormalsizeboxbacktick} -\newcommand{\hlboxunderscore}{ \hlnormalsizeboxunderscore} - -%% This corresponds to setting boxes=TRUE for highlight -\newsavebox{\hlbox} -\definecolor{hlBg}{rgb}{0.949019607843137,0.949019607843137,0.949019607843137} -\definecolor{hlBd}{rgb}{0.9,0.9,0.9} % border -\renewenvironment{Hchunk}{\vspace{0.5em}\noindent\begin{lrbox}{\hlbox}\begin{minipage}[b]{.9\textwidth}}% - {\end{minipage}\end{lrbox}\fcolorbox{hlBd}{hlBg}{\usebox{\hlbox}}\vspace{0.5em}} - -<>= -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -require(inline) -require(highlight) -require(Rcpp) -@ - -\author{Dirk Eddelbuettel \and Romain Fran\c{c}ois} -\title{Extending \pkg{Rcpp}} -\date{\pkg{Rcpp} version \Sexpr{prettyVersion} as of \Sexpr{prettyDate}} - -\begin{document} -\maketitle - -\abstract{ - \noindent - This note provides an overview of the steps programmers should follow to - extend \pkg{Rcpp} \citep{CRAN:Rcpp,JSS:Rcpp} for use with their own classes. This document - is based on our experience in extending \pkg{Rcpp} to work with the - \pkg{Armadillo} \citep{Sanderson:2010:Armadillo} classes, available in the separate package - \pkg{RcppArmadillo} \citep{CRAN:RcppArmadillo}. This document assumes - knowledge of \pkg{Rcpp} as well as some knowledge of \proglang{C++} - templates \citep{Abrahams+Gurtovoy:2004:TemplateMetaprogramming}. -} - - -\section{Introduction} - -\pkg{Rcpp} facilitates data interchange between \proglang{R} and -\proglang{C++} through the templated functions \texttt{Rcpp::as} (for -conversion of objects from \proglang{R} to \proglang{C++}) and -\texttt{Rcpp::wrap} (for conversion from \proglang{C++} to \proglang{R}). In -other words, we convert between the so-called \proglang{S}-expression -pointers (in type \texttt{SEXP}) to a templated \proglang{C++} type, and vice -versa. The corresponding function declarations are as follows: - -<>= -// conversion from R to C++ -template T as( SEXP x) ; - -// conversion from C++ to R -template SEXP wrap(const T& object) ; -@ - -These converters are often used implicitly, as in the following code chunk: - -<>= -code <- ' -#include -using namespace Rcpp; - -// [[Rcpp::export]] -List fx(List input){ // we get a list from R - -// pull std::vector from R list -// this is achieved through an implicit call to Rcpp::as -std::vector x = input["x"] ; - -// return an R list -// this is achieved through implicit call to Rcpp::wrap -return List::create( - _["front"] = x.front(), - _["back"] = x.back() - ); -} -' -writeLines( code, "code.cpp" ) -@ -<>= -external_highlight( "code.cpp", type = "LATEX", doc = FALSE ) -@ - -<<>>= -Rcpp::sourceCpp(file= "code.cpp") -input <- list( x = seq(1, 10, by = 0.5) ) -fx( input ) -@ - -The \pkg{Rcpp} converter function \texttt{Rcpp::as} and \texttt{Rcpp::wrap} have been -designed to be extensible to user-defined types and third-party types. - -\section[Extending Rcpp::wrap]{Extending \texttt{Rcpp::wrap} } - -The \pkg{Rcpp::wrap} converter is extensible in essentially two ways : intrusive -and non-intrusive. - -\subsection{Intrusive extension} - -When extending \pkg{Rcpp} with your own data type, the recommended way is to -implement a conversion to \texttt{SEXP}. This lets \texttt{Rcpp::wrap} know -about the new data type. The template meta programming (or TMP) dispatch is able to -recognize that a type is convertible to a \texttt{SEXP} and -\texttt{Rcpp::wrap} will use that conversion. - -The caveat is that the type must be declared before the main header -file \texttt{Rcpp.h} is included. - -<>= -#include - -class Foo { - public: - Foo() ; - - // this operator enables implicit Rcpp::wrap - operator SEXP() ; -} - -#include -@ - -This is called \emph{intrusive} because the conversion to \texttt{SEXP} -operator has to be declared within the class. - -\subsection{Non-intrusive extension} - -It is often desirable to offer automatic conversion to third-party types, over -which the developer has no control and can therefore not include a conversion -to \texttt{SEXP} operator in the class definition. - -To provide automatic conversion from \proglang{C++} to \proglang{R}, one must -declare a specialization of the \texttt{Rcpp::wrap} template between the -includes of \texttt{RcppCommon.h} and \texttt{Rcpp.h}. - -<>= -#include - -// third party library that declares class Bar -#include - -// declaring the specialization -namespace Rcpp { - template <> SEXP wrap( const Bar& ) ; -} - -// this must appear after the specialization, -// otherwise the specialization will not be seen by Rcpp types -#include -@ - -It should be noted that only the declaration is required. The implementation -can appear after the \texttt{Rcpp.h} file is included, and therefore take -full advantage of the \pkg{Rcpp} type system. - -Another non-intrusive option is to expose an external pointer. The macro -\texttt{RCPP\_EXPORT\_WRAP} provides an easy way to expose a \proglang{C++} class -to \proglang{R} as an external pointer. It can be used instead of specializing -\texttt{Rcpp::wrap}, and should not be used simultaneously. - -<>= -#include RcppCommon.h -#include foobar.h - -RCPP_EXPORT_WRAP(Bar); -@ - -\subsection{Templates and partial specialization} - -It is perfectly valid to declare a partial specialization for the -\texttt{Rcpp::wrap} template. The compiler will identify the appropriate -overload: - -<>= -#include - -// third party library that declares template class Bling -#include - -// declaring the partial specialization -namespace Rcpp { - namespace traits { - - template SEXP wrap( const Bling& ) ; - - } -} - -// this must appear after the specialization, -// otherwise the specialization will not be seen by Rcpp types -#include - -@ - - -\section[Extending Rcpp::as]{Extending \texttt{Rcpp::as}} - -Conversion from \proglang{R} to \proglang{C++} is also possible -in both intrusive and non-intrusive ways. - -\subsection{Intrusive extension} - -As part of its template meta programming dispatch logic, \pkg{Rcpp::as} -will attempt to use the constructor of the target class taking a \texttt{SEXP}. - -<>= -#include - -class Foo{ - public: - Foo() ; - - // this constructor enables implicit Rcpp::as - Foo(SEXP) ; -} - - -// this must appear after the specialization, -// otherwise the specialization will not be seen by Rcpp types -#include -@ - -\subsection{Non-intrusive extension} - -It is also possible to fully specialize \texttt{Rcpp::as} to enable -non-intrusive implicit conversion capabilities. - -<>= -#include - -// third party library that declares class Bar -#include - -// declaring the specialization -namespace Rcpp { - template <> Bar as( SEXP ) ; -} - -// this must appear after the specialization, -// otherwise the specialization will not be seen by Rcpp types -#include -@ - -Furthermore, another non-intrusive option is to opt for sharing an R -external pointer. The macro \texttt{RCPP\_EXPORT\_AS} provides an easy way to -extend \texttt{Rcpp::as} to expose \proglang{R} external pointers to -\proglang{C++}. It can be used instead of specializing \texttt{Rcpp::as}, and -should not be used simultaneously. - -<>= -#include RcppCommon.h -#include foobar.h - -RCPP_EXPORT_AS(Bar); -@ - -With this being said, there is one additional macro that can be used to -simultaneously define both \texttt{Rcpp::wrap} and \texttt{Rcpp::as} -specialization for an external pointer. The macro \texttt{RCPP\_EXPOSED\_CLASS} -can be use to transparently exchange a class between \proglang{R} and -\proglang{C++} as an external pointer. Do not simultaneously use it alongside -\texttt{RCPP\_EXPOSED\_AS}, \texttt{RCPP\_EXPOSED\_WRAP}, \texttt{Rcpp::wrap}, or -\texttt{Rcpp::as}. - - -\subsection{Templates and partial specialization} - -The signature of \texttt{Rcpp::as} does not allow partial specialization. -When exposing a templated class to \texttt{Rcpp::as}, the programmer must -specialize the \pkg{Rcpp::traits::Exporter} template class. The TMP dispatch -will recognize that a specialization of \texttt{Exporter} is available -and delegate the conversion to this class. \pkg{Rcpp} defines -the \texttt{Rcpp::traits::Exporter} template class as follows : - -<>= -namespace Rcpp { - namespace traits { - - template class Exporter{ - public: - Exporter( SEXP x ) : t(x){} - inline T get(){ return t ; } - - private: - T t ; - } ; - } -} -@ - -This is the reason why the default behavior of \texttt{Rcpp::as} is to -invoke the constructor of the type \texttt{T} taking a \texttt{SEXP}. - -Since partial specialization of class templates is allowed, we can expose -a set of classes as follows: - -<>= -#include - -// third party library that declares template class Bling -#include - -// declaring the partial specialization -namespace Rcpp { - namespace traits { - template class Exporter< Bling >; - } -} - -// this must appear after the specialization, -// otherwise the specialization will not be seen by Rcpp types -#include -@ - -Using this approach, the requirements for the \texttt{Exporter< Bling >} -class are: -\begin{itemize} -\item it should have a constructor taking a \texttt{SEXP} -\item it should have a methods called \texttt{get} that returns an instance -of the \texttt{Bling} type. -\end{itemize} - -<>= -unlink( "code.cpp" ) -@ - -\section{Summary} - -The \pkg{Rcpp} package greatly facilitates the transfer of objects between -\proglang{R} and \proglang{C++}. This note has shown how to extend \pkg{Rcpp} -to either user-defined or third-party classes via the \texttt{Rcpp::as} and -\texttt{Rcpp::wrap} template functions. Both intrusive and non-intrusive -approaches were discussed. - -\bibliographystyle{plainnat} -\bibliography{\Sexpr{Rcpp:::bib()}} - -\end{document} - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-extending.pdf b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-extending.pdf deleted file mode 100644 index 62d914d..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-extending.pdf and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-introduction.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-introduction.R deleted file mode 100644 index b8674f0..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-introduction.R +++ /dev/null @@ -1,11 +0,0 @@ -### R code from vignette source 'Rcpp-introduction.Rnw' - -################################################### -### code chunk number 1: prelim -################################################### -library(Rcpp) -rcpp.version <- packageDescription("Rcpp")$Version -rcpp.date <- packageDescription("Rcpp")$Date -now.date <- strftime(Sys.Date(), "%B %d, %Y") - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-introduction.Rnw b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-introduction.Rnw deleted file mode 100644 index dd18b55..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-introduction.Rnw +++ /dev/null @@ -1,1077 +0,0 @@ -%% use JSS class -- use 'nojss' to turn off header -\documentclass[shortnames,nojss,article]{jss} -\usepackage{booktabs,flafter,thumbpdf} -%\VignetteIndexEntry{Rcpp-introduction} -%\VignetteKeywords{Rcpp, foreign function interface, .Call, C++, R} -%\VignetteDepends{Rcpp} -\SweaveOpts{concordance=FALSE} - -\author{Dirk Eddelbuettel\\Debian Project \And Romain Fran\c{c}ois\\\proglang{R} Enthusiasts} -\Plainauthor{Dirk Eddelbuettel, Romain Fran\c{c}ois} - -\title{\pkg{Rcpp}: Seamless \proglang{R} and \proglang{C++} Integration} -\Plaintitle{Rcpp: Seamless R and C++ Integration} - -\Abstract{ - The \pkg{Rcpp} package simplifies integrating \proglang{C++} code with \proglang{R}. It - provides a consistent \proglang{C++} class hierarchy that maps various types of \proglang{R} - objects (vectors, matrices, functions, environments, \dots) to dedicated \proglang{C++} - classes. Object interchange between \proglang{R} and \proglang{C++} is managed by - simple, flexible and extensible concepts which include broad support for - \proglang{C++} Standard Template Library idioms. \proglang{C++} code can both be - compiled, linked and loaded on the fly, or added via packages. - Flexible error and exception code handling is provided. - \pkg{Rcpp} substantially lowers the barrier for programmers wanting to - combine \proglang{C++} code with \proglang{R}. -} - -\Keywords{\proglang{R}, \proglang{C++}, foreign function interface, \code{.Call}} -\Plainkeywords{R, C++, foreign function interface, .Call} - -\Volume{40} -\Issue{8} -\Month{April} -\Year{2011} -\Submitdate{2010-11-15} -\Acceptdate{2011-03-21} - -\Address{ - Dirk Eddelbuettel \\ - Debian Project \\ - River Forest, IL, United States of America\\ - E-mail: \email{edd@debian.org}\\ - URL: \url{http://dirk.eddelbuettel.com/}\\ - - Romain Fran\c{c}ois\\ - Professional \proglang{R} Enthusiast\\ - 1 rue du Puits du Temple\\ - 34 000 Montpellier, France \\ - E-mail: \email{romain@r-enthusiasts.com}\\ - URL: \url{http://romainfrancois.blog.free.fr/} -} - -%% need no \usepackage{Sweave.sty} - -<>= -library(Rcpp) -rcpp.version <- packageDescription("Rcpp")$Version -rcpp.date <- packageDescription("Rcpp")$Date -now.date <- strftime(Sys.Date(), "%B %d, %Y") -@ -% - - -\begin{document} - -\vspace*{-0.25cm} - -\section{Introduction} - -\proglang{R} \citep{R:Main} is an extensible system. -The `Writing \proglang{R} Extensions' manual \citep{R:Extensions} -describes in detail how to augment \proglang{R} with compiled code, -focusing mostly on the \proglang{C} language, but also mentioning -\proglang{C++} and \proglang{Fortran}. The \proglang{R} application programming -interface (API) described in `Writing \proglang{R} Extensions' is -based on a set of functions and macros operating on \code{SEXP} (pointers to -\code{SEXPREC} or `\proglang{S} expression' structures, see the `\proglang{R} Language' -manual \citealp{R:Language} for details) which are the internal -representation of \proglang{R} objects. -In this article, we discuss the functionality of the \pkg{Rcpp} -package \citep{CRAN:Rcpp}, which simplifies the usage of \proglang{C++} code -in \proglang{R}. Combining \proglang{R} and \proglang{C++} is not a new idea, so we start with -a short review of other approaches and give some historical -background on the development of \pkg{Rcpp}. - -The \pkg{Rcpp} package provides a consistent API for seamlessly accessing, -extending or modifying \proglang{R} objects at the \proglang{C++} level. The API is a rewritten -and extended version of an earlier API which we refer to as the `classic -\pkg{Rcpp} API'. It is still provided in the \pkg{RcppClassic} package \citep{CRAN:RcppClassic} -to ensure compatibility, but its use is otherwise deprecated. -All new development should use the richer second API which -is enclosed in the \pkg{Rcpp} \proglang{C++} -namespace, and corresponds to the redesigned code base. -This article highlights some of the key design and implementation choices of -the new API: Lightweight encapsulation of \proglang{R} objects in \proglang{C++} classes, automatic -garbage collection strategy, code inlining, data interchange between \proglang{R} and -\proglang{C++}, and error handling. - -Several examples are included to illustrate the benefits of using \pkg{Rcpp} -as opposed to the traditional \proglang{R} API. Many more examples are available within -the package, both as explicit examples and as part of the numerous unit tests. -% -The \pkg{Rcpp} package is available from the Comprehensive \proglang{R} Archive Network (CRAN) -at \url{http://CRAN.R-project.org/package=Rcpp}. - -\makeatletter -\if@nojss - This vignette corresponds to the paper published in the \textsl{Journal of - Statistical Software}. It is currently still identical to - the published paper. Over time, this vignette version may receive minor - updates. For citations, please use the \cite{JSS:Rcpp} or - \cite{Eddelbuettel:2013:Rcpp}; details are also provided in \proglang{R} via - \texttt{citation("Rcpp")}. - - This version corresponds to \pkg{Rcpp} version \Sexpr{rcpp.version} and was - typeset on \Sexpr{now.date}. -\fi -\makeatother - - -\subsection{Historical context} - -\pkg{Rcpp} first appeared in 2005 as a contribution (by Dominick Samperi) to the -\pkg{RQuantLib} package \citep{CRAN:RQuantLib} and became a CRAN package -in early 2006. Several releases (all by Samperi) followed in quick succession -under the name \pkg{Rcpp}. The package was then renamed to -\pkg{RcppTemplate}; several more releases followed during 2006 under the new -name. However, no further releases were made during 2007, 2008 or most of -2009. Following a few updates in late 2009, it was withdrawn from CRAN. - -Given the continued use of the package, Eddelbuettel decided to revitalize it. New -releases, using the initial name \pkg{Rcpp}, started in November 2008. These -included an improved build and distribution process, additional -documentation, and new functionality---while retaining the existing -`classic \pkg{Rcpp}' interface. While not described here, this API will -be provided for the foreseeable future via the \pkg{RcppClassic} package. - -Reflecting evolving \proglang{C++} coding standards \citep[see][]{Meyers:2005:EffectiveC++}, -Eddelbuettel and Fran\c{c}ois started a significant redesign of the -code base in 2009. This added numerous new features several of which are described -in this article as well as in multiple -vignettes included with the package. This new API is our current focus, -and we intend to both extend and support the API in future development of the -\pkg{Rcpp} package. - -\subsection{Related work} - -Integration of \proglang{C++} and \proglang{R} has been addressed by several authors; the earliest -published reference is probably \cite{Bates+DebRoy:2001:C++Classes}. -An unpublished paper by \cite{Java+Gaile+Manly:2007:RCpp} expresses several ideas -that are close to some of our approaches, though not yet fully fleshed out. -The \pkg{Rserve} package \citep{Urbanek:2003:Rserve,CRAN:Rserve} acts as a -socket server for \proglang{R}. On the server side, \pkg{Rserve} translates \proglang{R} data -structures into a binary serialization format and uses TCP/IP for -transfer. On the client side, objects are reconstructed as instances of \proglang{Java} -or \proglang{C++} classes that emulate the structure of \proglang{R} objects. - -The packages \pkg{rcppbind} \citep{Liang:2008:rcppbind}, \pkg{RAbstraction} -\citep{Armstrong:2009:RAbstraction} and \pkg{RObjects} -\citep{Armstrong:2009:RObjects} are all implemented using \proglang{C++} templates. -None of them have matured to the point of a CRAN release. -\pkg{CXXR} \citep{Runnalls:2009:CXXR} approaches this topic from the other direction: -Its aim is to completely refactor \proglang{R} on a stronger \proglang{C++} foundation. -\pkg{CXXR} is therefore concerned with all aspects of the \proglang{R} interpreter, -read-eval-print loop (REPL), and threading; object interchange between \proglang{R} and \proglang{C++} is but one -part. A similar approach is discussed by \cite{TempleLang:2009:ModestProposal} -who suggests making low-level internals extensible by package developers in -order to facilitate extending \proglang{R}. -\cite{TempleLang:2009:RGCCTranslationUnit}, using compiler output for -references on the code in order to add bindings and wrappers, offers -a slightly different angle. - -\subsection[Rcpp use cases]{\pkg{Rcpp} use cases} -\label{sec:classic_rcpp} - -The core focus of \pkg{Rcpp} has always been on helping the -programmer to more easily add \proglang{C++}-based functions. -Here, we use `function' in the standard mathematical sense of providing -results (output) given a set of parameters or data (input). -This was -facilitated from the earliest releases using \proglang{C++} classes for receiving -various types of \proglang{R} objects, converting them to \proglang{C++} objects and allowing the -programmer to return the results to \proglang{R} with relative ease. - -This API therefore supports two typical use cases. First, existing \proglang{R} code -may be replaced by equivalent \proglang{C++} code in order to reap -performance gains. This case is conceptually easy when there are -(built- or run-time) dependencies on other \proglang{C} or \proglang{C++} libraries. It typically -involves setting up data and parameters---the right-hand side components of a -function call---before making the call in order to provide the result that is -to be assigned to the left-hand side. Second, \pkg{Rcpp} facilitates calling -functions provided by other libraries. The use resembles the first case but -with an additional level of abstraction: data -and parameters are passed via \pkg{Rcpp} to a function set-up to call code -from an external library. - -Apart from this `vertical mode' of calling \proglang{C++} from \proglang{R}, additional -features in the new API also support a more `horizontal mode' of directly -calling \pkg{Rcpp} objects. This was motivated by the needs of other -projects such as \pkg{RInside} \citep{CRAN:RInside} for easy embedding of \proglang{R} -in \proglang{C++} applications and \pkg{RProtoBuf} \citep{CRAN:RProtoBuf} to -interface with the Protocol Buffers library. This use will be touched upon -in the next section, but a more detailed discussion is outside the scope of -this paper. Lastly, the more recent additions `\pkg{Rcpp} modules' and `\pkg{Rcpp} sugar' -also expand the use cases; see Section~\ref{sec:ongoing} below. - -\section[The Rcpp API]{The \pkg{Rcpp} API} -\label{sec:new_rcpp} - -\subsection{A first example} - -We can illustrate the \pkg{Rcpp} API by revisiting the convolution example -from the `Writing \proglang{R} Extensions' manual \citep[Chapter 5]{R:Extensions}. Using -\pkg{Rcpp}, this function can be written as follows: -% -\begin{Code} -#include - -RcppExport SEXP convolve3cpp(SEXP a, SEXP b) { - Rcpp::NumericVector xa(a); - Rcpp::NumericVector xb(b); - int n_xa = xa.size(), n_xb = xb.size(); - int nab = n_xa + n_xb - 1; - Rcpp::NumericVector xab(nab); - - for (int i = 0; i < n_xa; i++) - for (int j = 0; j < n_xb; j++) - xab[i + j] += xa[i] * xb[j]; - - return xab; -} -\end{Code} -% -We can highlight several aspects. -\begin{enumerate} -\item Only a single header file - \code{Rcpp.h} is needed to use the \pkg{Rcpp} API. -\item \code{RcppExport} is a convenience macro helping with calling a - \proglang{C} function from \proglang{C++}. -\item Given two - arguments of type \code{SEXP}, a third is returned (as using only - \code{SEXP} types for input and output is prescribed by the \code{.Call()} - interface of the \proglang{R} API). -\item Both inputs are - converted to \proglang{C++} vector types provided by \pkg{Rcpp} (and we have more to say about these - conversions below). -\item The - usefulness of these classes can be seen when we query the vectors directly - for their size---using the \code{size()} member function---in order to - reserve a new result type of appropriate length, - and with the use of the - \verb|operator[]| to extract and set individual elements of the vector. -\item The computation itself is - straightforward embedded looping just as in the original examples in the - `Writing \proglang{R} Extensions' manual \citep{R:Extensions}. -\item The return conversion - from the \code{NumericVector} to the \code{SEXP} type is also automatic. -\end{enumerate} - -We argue that this \pkg{Rcpp}-based usage is much easier to read, write and debug than the -\proglang{C} macro-based approach supported by \proglang{R} itself. - - - -\subsection[Rcpp class hierarchy]{\pkg{Rcpp} class hierarchy} - -The \code{Rcpp::RObject} class is the basic class of the new \pkg{Rcpp} API. -An instance of the \code{RObject} class encapsulates an \proglang{R} object -(itself represented by the \proglang{R} type \code{SEXP}), exposes methods that are appropriate for all types -of objects and transparently manages garbage collection. - -The most important aspect of the \code{RObject} class is that it is -a very thin wrapper around the \code{SEXP} it encapsulates. The -\code{SEXP} is indeed the only data member of an \code{RObject}. The -\code{RObject} class does not interfere with the way \proglang{R} manages its -memory and does not perform copies of the object into a suboptimal -\proglang{C++} representation. Instead, it merely acts as a proxy to the -object it encapsulates so that methods applied to the \code{RObject} -instance are relayed back to the \code{SEXP} in terms of the standard -\proglang{R} API. - -The \code{RObject} class takes advantage of the explicit life cycle of -\proglang{C++} objects to manage exposure of the underlying \proglang{R} object to the -garbage collector. The \code{RObject} effectively treats -its underlying \code{SEXP} as a resource. -The constructor of the \code{RObject} class takes -the necessary measures to guarantee that the underlying \code{SEXP} -is protected from the garbage collector, and the destructor -assumes the responsibility to withdraw that protection. - -By assuming the entire responsibility of garbage collection, \pkg{Rcpp} -relieves the programmer from writing boiler plate code to manage -the protection stack with \code{PROTECT} and \code{UNPROTECT} macros. - -The \code{RObject} class defines a set of member functions applicable -to any \proglang{R} object, regardless of its type. This ranges from -querying properties of the object (\texttt{isNULL}, \texttt{isObject}, -\texttt{isS4}), management of the attributes -(\texttt{attributeNames}, \texttt{hasAttribute}, \texttt{attr}) to -handling of slots\footnote{Member functions dealing with slots -are only applicable to \proglang{S}4 objects; otherwise an exception is thrown.} -(\texttt{hasSlot}, \texttt{slot}). - -\subsection{Derived classes} - -Internally, an \proglang{R} object must have one type amongst the set of -predefined types, commonly referred to as SEXP types. The `\proglang{R} Internals' -manual \citep{R:Internals} documents these various types. -\pkg{Rcpp} associates a dedicated \proglang{C++} class for most SEXP types, and -therefore only exposes functionality that is relevant to the \proglang{R} object -that it encapsulates. - -For example \code{Rcpp::Environment} contains -member functions to manage objects in the associated environment. -Similarly, classes related to vectors---\code{IntegerVector}, \code{NumericVector}, -\code{RawVector}, \code{LogicalVector}, \code{CharacterVector}, -\code{GenericVector} (also known as \code{List}) and -\code{ExpressionVector}---expose functionality to extract and set values from the vectors. - -The following sections present typical uses of \pkg{Rcpp} classes in -comparison with the same code expressed using functions and macros of the \proglang{R} API. - -\subsection{Numeric vectors} - -The next code snippet is taken from `Writing \proglang{R} Extensions' -\citep[Section 5.9.1]{R:Extensions}. It allocates a \code{numeric} vector of two elements -and assigns some values to it using the \proglang{R} API. -% -\begin{Code} -SEXP ab; -PROTECT(ab = allocVector(REALSXP, 2)); -REAL(ab)[0] = 123.45; -REAL(ab)[1] = 67.89; -UNPROTECT(1); -\end{Code} -% -Although this is one of the simplest examples in `Writing \proglang{R} Extensions', -it seems verbose and yet it is not obvious at first sight what is happening. -Memory is allocated by \code{allocVector}; we must also supply it with -the type of data (\code{REALSXP}) and the number of elements. Once -allocated, the \code{ab} object must be protected from garbage -collection. -Lastly, the \code{REAL} macro returns a pointer to the -beginning of the actual array; its indexing does not resemble either \proglang{R} or -\proglang{C++}. - -The code can be simplified using the \code{Rcpp::NumericVector} class: -% -\begin{Code} -Rcpp::NumericVector ab(2); -ab[0] = 123.45; -ab[1] = 67.89; -\end{Code} -% -The code contains fewer idiomatic decorations. The \code{NumericVector} -constructor is given the number of elements the vector contains (2), which -hides the call to the \code{allocVector} in the original code example. Also hidden is -protection of the object from garbage collection, which is a behavior that -\code{NumericVector} inherits from \code{RObject}. Values are assigned to -the first and second elements of the vector as \code{NumericVector} overloads -the \code{operator[]}. - -The snippet can also be written more concisely as a single statement using the \code{create} -static member function of the \code{NumericVector} class: -% -\begin{Code} -Rcpp::NumericVector ab = Rcpp::NumericVector::create(123.45, 67.89); -\end{Code} - - -\subsection{Character vectors} - -A second example deals with character vectors and emulates this \proglang{R} code: -% -\begin{CodeInput} -R> c("foo", "bar") -\end{CodeInput} -% -Using the traditional \proglang{R} API, the vector can be allocated and filled as such: -% -\begin{Code} -SEXP ab; -PROTECT(ab = allocVector(STRSXP, 2)); -SET_STRING_ELT( ab, 0, mkChar("foo") ); -SET_STRING_ELT( ab, 1, mkChar("bar") ); -UNPROTECT(1); -\end{Code} -% -This imposes on the programmer knowledge of \code{PROTECT}, \code{UNPROTECT}, -\code{SEXP}, \code{allocVector}, \code{SET\_STRING\_ELT}, and \code{mkChar}. -% -Using the \code{Rcpp::CharacterVector} class, we can express the same -code more concisely: -% -\begin{Code} -Rcpp::CharacterVector ab(2); -ab[0] = "foo"; -ab[1] = "bar"; -\end{Code} - -\section[R and C++ data interchange]{\proglang{R} and \proglang{C++} data interchange} - -In addition to classes, the \pkg{Rcpp} package contains two -functions to perform conversion of \proglang{C++} objects to \proglang{R} objects and back. - -\subsection[C++ to R: wrap]{\proglang{C++} to \proglang{R}: \code{wrap}} - -The \proglang{C++} to \proglang{R} conversion is performed by the \code{Rcpp::wrap} templated -function. It uses advanced template metaprogramming techniques\footnote{A - discussion of template metaprogramming - \citep{Vandevoorde+Josuttis:2003:Templates,Abrahams+Gurtovoy:2004:TemplateMetaprogramming} is beyond the - scope of this article.} to convert a wide and extensible set of types and -classes to the most appropriate type of \proglang{R} object. The signature of the -\code{wrap} template is as follows: -% -\begin{Code} -template SEXP wrap(const T& object); -\end{Code} -% -The templated function takes a reference to a `wrappable' -object and converts this object into a \code{SEXP}, which is what \proglang{R} expects. -Currently wrappable types are: -\begin{itemize} -\item primitive types: \code{int}, \code{double}, \code{bool}, \dots which are converted -into the corresponding atomic \proglang{R} vectors; -\item \code{std::string} objects which are converted to \proglang{R} atomic character vectors; -\item Standard Template Library (STL) containers such as \code{std::vector} or \code{std::map}, -as long as the template parameter type \code{T} is itself wrappable; -\item STL maps which use \code{std::string} for keys -({e.g.}, \code{std::map}); as long as -the type \code{T} is wrappable; -\item any type that implements implicit conversion to \code{SEXP} through the -\code{operator SEXP()}; -\item any type for which the \code{wrap} template is -fully specialized. -\end{itemize} - -Wrappability of an object type is resolved at compile time using -modern techniques of template meta programming and class traits. The -\code{Rcpp-extending} vignette in the \pkg{Rcpp} package discusses in depth how to extend \code{wrap} -to third-party types. The \pkg{RcppArmadillo} -\citep*{CRAN:RcppArmadillo} and \pkg{RcppGSL} \citep{CRAN:RcppGSL} packages -feature several examples. -The following segment of code illustrates that the design allows -composition: - -\begin{Code} -RcppExport SEXP someFunction() { - std::vector > v; - std::map m1; - std::map m2; - - m1["foo"]=1; - m1["bar"]=2; - m2["foo"]=1; - m2["bar"]=2; - m2["baz"]=3; - - v.push_back( m1 ); - v.push_back( m2 ); - return Rcpp::wrap( v ); -} -\end{Code} -% -In this example, the STL types \verb+vector+ and \verb+map+ are used to -create a list of two named vectors. The member function \verb+push_back+ -insert a given element into a vector. This example is equivalent to the -result of this \proglang{R} statement: -% -\begin{Code} -list(c(bar = 2L, foo = 1L), c(bar = 2L, baz = 3L, foo = 1L)) -\end{Code} - - -\subsection[R to C++: as]{\proglang{R} to \proglang{C++}: \code{as}} - -The reverse conversion from an \proglang{R} object to a \proglang{C++} object is implemented by variations of the -\code{Rcpp::as} template whose signature is: -% -\begin{Code} -template T as(SEXP x); -\end{Code} -% -It offers less flexibility and currently -handles conversion of \proglang{R} objects into primitive types ({e.g.}, \code{bool}, \code{int}, \code{std::string}, \dots), -STL vectors of primitive types ({e.g.}, \code{std::vector}, -\code{std::vector}, \dots) and arbitrary types that offer -a constructor that takes a \code{SEXP}. In addition \code{as} can -be fully or partially specialized to manage conversion of \proglang{R} data -structures to third-party types as can be seen for example in the -\pkg{RcppArmadillo} package which eases transfer of \proglang{R} matrices and vectors to -the optimised data structures in the \pkg{Armadillo} linear algebra library \citep{Sanderson:2010:Armadillo}. - - -\subsection{Implicit use of converters} - -The converters offered by \code{wrap} and \code{as} provide a very -useful framework to implement code logic in terms of \proglang{C++} -data structures and then explicitly convert data back to \proglang{R}. - -In addition, the converters are also used implicitly -in various places in the \code{Rcpp} API. -Consider the following code that uses the \code{Rcpp::Environment} class to -interchange data between \proglang{C++} and \proglang{R}. It accesses a vector -\texttt{x} from the global environment, creates an STL \texttt{map} of string -types and pushes this back to \proglang{R}: -% -\begin{Code} -Rcpp::Environment global = Rcpp::Environment::global_env(); -std::vector vx = global["x"]; - -std::map map; -map["foo"] = "oof"; -map["bar"] = "rab"; - -global["y"] = map; -\end{Code} -% -In the first part of the example, the code extracts a -\code{std::vector} from the global environment. In order to achieve this, -the \code{operator[]} of \code{Environment} uses the proxy pattern -\citep{Meyers:1995:MoreEffectiveC++} -to distinguish between left hand side (LHS) and right hand side (RHS) use. - -The output of the \code{operator[]} is an instance of the nested class -\code{Environment::Binding}. This class defines a templated implicit conversion -operator. It is this conversion operator which allows a \code{Binding} -object to be assigned to any type that \code{Rcpp::as} is able to handle. - -In the last part of the example, the LHS use of the \code{Binding} instance is -implemented through its assignment operator. This is also templated and uses -\code{Rcpp::wrap} to perform the conversion to a \code{SEXP} that can be -assigned to the requested symbol in the global environment. - -The same mechanism is used throughout the API. Examples include access/modification -of object attributes, slots, elements of generic vectors (lists), -function arguments, nodes of dotted pair lists, language calls and more. - -\section{Function calls} -\label{sec:functions} - -\begin{table}[t!] - \begin{minipage}[t]{0.465\linewidth} - \centering{\underline{Environment: Using the \pkg{Rcpp} API}} - \begin{Code} -Environment stats("package:stats"); -Function rnorm = stats["rnorm"]; -return rnorm(10, - Named("sd", 100.0)); - \end{Code} -\end{minipage} - \begin{minipage}{0.06\linewidth} - \phantom{XXX} - \end{minipage} - \begin{minipage}[t]{0.465\linewidth} - \centering{\underline{Environment: Using the \proglang{R} API}} - \begin{Code} -SEXP stats = PROTECT( - R_FindNamespace( - mkString("stats"))); -SEXP rnorm = PROTECT( - findVarInFrame(stats, - install("rnorm"))); -SEXP call = PROTECT( - LCONS( rnorm, - CONS(ScalarInteger(10), - CONS(ScalarReal(100.0), - R_NilValue)))); -SET_TAG(CDDR(call),install("sd")); -SEXP res = PROTECT(eval(call, - R_GlobalEnv)); -UNPROTECT(4); -return res; - \end{Code} - \end{minipage} - -\bigskip - - \begin{minipage}[t]{0.465\linewidth} - \centering{\underline{Language: Using the \pkg{Rcpp} API}} - \begin{Code} -Language call("rnorm", 10, - Named("sd",100.0)); -return call.eval(); - \end{Code} - \end{minipage} - \begin{minipage}{0.06\linewidth} - \phantom{XXX} - \end{minipage} - \begin{minipage}[t]{0.465\linewidth} - \centering{\underline{Language: Using the \proglang{R} API}} - \begin{Code} -SEXP call = PROTECT( - LCONS(install("rnorm"), - CONS(ScalarInteger(10), - CONS(ScalarReal(100.0), - R_NilValue)))); -SET_TAG(CDDR(call),install("sd")); -SEXP res = PROTECT(eval(call, - R_GlobalEnv)); -UNPROTECT(2); -return res; - \end{Code} - \end{minipage} - -\bigskip - - \begin{minipage}[t]{0.465\linewidth} - \centering{\underline{Sugar: Using the \pkg{Rcpp} API}} - \begin{Code} -RNGScope scope; -return rnorm(10, 0, 100); - \end{Code} -\end{minipage} - \begin{minipage}{0.06\linewidth} - \phantom{XXX} - \end{minipage} - \begin{minipage}[t]{0.465\linewidth} - \centering{\underline{Sugar: Using the \proglang{R} API}} - - \medskip - (not applicable) - \end{minipage} - -\bigskip - - \caption{\pkg{Rcpp} versus the \proglang{R} API: Five ways of calling - \code{rnorm(10L, sd = 100)} in \proglang{C}/\proglang{C++}.} - \label{fig:rnormCode} - \medskip \small - Note that we have removed the \code{Rcpp::} prefix for readability; this corresponds to adding a directive - \texttt{using namespace Rcpp;} in the code. The versions that use callbacks to \proglang{R} do not require handling - of the state of the random number generator. The version that uses \pkg{Rcpp} sugar requires it, which - is done via the instantiation of the \code{RNGScope} variable. -\end{table} - -The next example shows how to use \pkg{Rcpp} to emulate the \proglang{R} code -\code{rnorm(10L, sd = 100.0)}. -As shown in Table~\ref{fig:rnormCode}, the code can be expressed in several -ways in either \pkg{Rcpp} or the standard \proglang{R} API. The first version shows the -use of the \code{Environment} and \code{Function} classes by -\pkg{Rcpp}. -The second version shows the use of the \code{Language} class, which -manages calls (LANGSXP). -For comparison, we also show both versions using the standard \proglang{R} API. -Finally, we also show a variant using `\pkg{Rcpp} sugar', a topic which is -discussed in Sections~\ref{sec:perfcomp} and \ref{sec:ongoing} below. - -This example illustrates that the \pkg{Rcpp} API permits us to work with code -that is easier to read, write and maintain. More examples are available as -part of the documentation included in the \pkg{Rcpp} package, as well as -among its over seven hundred and fifty unit tests. - -\section{Using code `inline'} -\label{sec:inline} - -Extending \proglang{R} with compiled code requires a mechanism for reliably compiling, -linking, and loading the code. While using a package is preferable in the long run, -it may be too involved for quick explorations. An alternative is -provided by the \pkg{inline} package \citep{CRAN:inline} which compiles, -links and loads a \proglang{C}, \proglang{C++} or \proglang{Fortran} function---directly from the \proglang{R} prompt -using simple functions \code{cfunction} and \code{cxxfunction}. The latter provides an extension which -works particularly well with \pkg{Rcpp} via so-called `plugins' which provide -information about additional header file and -library locations. - -The use of \pkg{inline} is possible as \pkg{Rcpp} can be installed and -updated just like any other \proglang{R} package using, for examples, the -\code{install.packages()} function for initial installation as well as -\code{update.packages()} for upgrades. So even though \proglang{R}/\proglang{C++} interfacing -would otherwise require source code, the \pkg{Rcpp} library is always provided -ready for use as a pre-built library through the CRAN package -mechanism.\footnote{This presumes a platform for which pre-built binaries are - provided. \pkg{Rcpp} is available in binary form for Windows and OS~X users from - CRAN, and as a \code{.deb} package for Debian and Ubuntu users. For other systems, the - \pkg{Rcpp} library is automatically built from source during installation - or upgrades.} - -The library and header files provided by \pkg{Rcpp} for use by other packages -are installed along with the \pkg{Rcpp} package. The \code{LinkingTo:}~\code{Rcpp} -directive in the \code{DESCRIPTION} file lets \proglang{R} properly reference the header files. -The \pkg{Rcpp} package provides appropriate information for the \code{-L} -switch needed for linking via the function \code{Rcpp:::LdFlags()}. -It can be used by \code{Makevars} files of other -packages, and \pkg{inline} makes use of it internally so that all of this is -done behind the scenes without the need for explicitly setting compiler or -linker options. - -The convolution example provided above can be rewritten for use by -\pkg{inline} as shown below. The function body is provided by the \proglang{R} character -variable \code{src}, the function header is defined by the argument -\code{signature}, and we only need to enable \code{plugin = "Rcpp"} to obtain a -new \proglang{R} function \code{fun} based on the \proglang{C++} code in \code{src}: -% -\begin{CodeChunk} -\begin{CodeInput} -R> src <- ' -+ Rcpp::NumericVector xa(a); -+ Rcpp::NumericVector xb(b); -+ int n_xa = xa.size(), n_xb = xb.size(); -+ -+ Rcpp::NumericVector xab(n_xa + n_xb - 1); -+ for (int i = 0; i < n_xa; i++) -+ for (int j = 0; j < n_xb; j++) -+ xab[i + j] += xa[i] * xb[j]; -+ return xab; -+ ' -R> fun <- cxxfunction(signature(a = "numeric", b = "numeric"), -+ src, plugin = "Rcpp") -R> fun(1:3, 1:4) -\end{CodeInput} -\begin{CodeOutput} -[1] 1 4 10 16 17 12 -\end{CodeOutput} -\end{CodeChunk} -% -With one assignment to the \proglang{R} variable \code{src}, and one call of the \proglang{R} function -\code{cxxfunction} (provided by the \pkg{inline} package), we have created a new \proglang{R} -function \code{fun} that uses the \proglang{C++} code we assigned to -\code{src}---and all this functionality can be used directly from the \proglang{R} -prompt making prototyping with \proglang{C++} functions straightforward. - -\textsl{Update}: \pkg{Rcpp} version 0.10.0 and later contain new and powerful feature -called 'Rcpp Attributes' which provides an even more powerful mechanism; see -\cite{CRAN:Rcpp:Attributes} for more details. - -\section{Using Standard Template Library algorithms} - -The STL offers a variety of generic -algorithms designed to be used on ranges of elements -\citep{Plauger+Et+Al:2000:STL}. A range is any sequence of objects that can be -accessed through iterators or pointers. All \pkg{Rcpp} classes from the new -API representing vectors (including lists) can produce ranges through their -member functions \code{begin()} and \code{end()}, effectively supporting -iterating over elements of an \proglang{R} vector. - -The following code illustrates how \pkg{Rcpp} might be used -to emulate a -simpler\footnote{The version of \code{lapply} does not allow use of the -ellipsis (\code{...}).} version of \code{lapply} -using the \code{transform} algorithm from the STL. -% -\begin{CodeChunk} -\begin{CodeInput} -R> src <- ' -+ Rcpp::List input(data); -+ Rcpp::Function f(fun); -+ Rcpp::List output(input.size()); -+ std::transform(input.begin(), input.end(), output.begin(), f); -+ output.names() = input.names(); -+ return output; -+ ' -R> cpp_lapply <- cxxfunction(signature(data = "list", fun = "function"), -+ src, plugin = "Rcpp") -\end{CodeInput} -\end{CodeChunk} -% -We can now use this \code{cpp_lapply} function to calculate a summary of each -column of the \code{faithful} data set included with \proglang{R}. -% -\begin{CodeInput} -R> cpp_lapply(faithful, summary) -\end{CodeInput} -\begin{CodeOutput} -$eruptions - Min. 1st Qu. Median Mean 3rd Qu. Max. -1.600 2.163 4.000 3.488 4.454 5.100 - -$waiting - Min. 1st Qu. Median Mean 3rd Qu. Max. - 43.0 58.0 76.0 70.9 82.0 96.0 -\end{CodeOutput} - - -\section{Error handling} - -Code that uses both \proglang{R} and \proglang{C++} has to deal with two distinct -error handling models. \pkg{Rcpp} simplifies this and allows both -systems to work together. - -\subsection[C++ exceptions in R]{\proglang{C++} exceptions in \proglang{R}} - -The internals of the \proglang{R} condition mechanism and the implementation of -\proglang{C++} exceptions are both based on a layer above POSIX jumps. These layers -both assume total control over the call stack and should not be used together -without extra precaution. \pkg{Rcpp} contains facilities to combine both systems -so that \proglang{C++} exceptions are caught and recycled into the \proglang{R} condition -mechanism. - -\pkg{Rcpp} defines the \code{BEGIN\_RCPP} and \code{END\_RCPP} macros that should -be used to bracket code that might throw \proglang{C++} exceptions. -% -\begin{Code} -RcppExport SEXP fun( SEXP x ) { -BEGIN_RCPP - int dx = Rcpp::as(x); - if( dx > 10 ) - throw std::range_error("too big"); - return Rcpp::wrap( dx * dx); -END_RCPP -} -\end{Code} -% -The macros are simply defined to avoid code repetition. They expand to -simple \code{try}/\code{catch} blocks so that the above example becomes: -% -\begin{Code} -RcppExport SEXP fun( SEXP x ) { - try { - int dx = Rcpp::as(x); - if( dx > 10 ) - throw std::range_error("too big"); - return Rcpp::wrap( dx * dx); - } catch( std::exception& __ex__ ) { - forward_exception_to_r( __ex__ ); - } catch(...) { - ::Rf_error( "c++ exception (unknown reason)" ); - } -} -\end{Code} -% -Using \code{BEGIN\_RCPP} and \code{END\_RCPP}---or the expanded -versions---guarantees that the stack is first unwound in terms of \proglang{C++} -exceptions, before the problem is converted to the standard \proglang{R} error -management system using the function \code{Rf\_error} of the \proglang{R} API. - -The \code{forward\_exception\_to\_r} function uses run-time type information to -extract information about the class of the \proglang{C++} exception and its message so that -dedicated handlers can be installed on the \proglang{R} side. -% -\begin{CodeChunk} -\begin{CodeInput} -R> f <- function(x) .Call("fun", x) -R> tryCatch(f(12), "std::range_error" = function(e) { conditionMessage(e) }) -\end{CodeInput} -\begin{CodeOutput} -[1] "too big" -\end{CodeOutput} -\begin{CodeInput} -R> tryCatch(f(12), "std::range_error" = function(e) { class(e) }) -\end{CodeInput} -\begin{CodeOutput} -[1] "std::range_error" "C++Error" "error" "condition" -\end{CodeOutput} -\end{CodeChunk} -% -A serious limitation of this approach is the lack of support for calling -handlers. \proglang{R} calling handlers are also based on POSIX jumps, and using both -calling handlers from the \proglang{R} engine as well \proglang{C++} exception forwarding might -lead to undetermined results. Future versions of \pkg{Rcpp} might attempt to -to improve this issue. - -\subsection[R errors in C++]{\proglang{R} errors in \proglang{C++}} - -\proglang{R} itself currently does not offer \proglang{C}-level mechanisms to deal with errors. To -overcome this problem, \pkg{Rcpp} uses the \code{Rcpp\_eval} -function to evaluate an \proglang{R} expression in an R-level \code{tryCatch} -block. The error, if any, that occurs while evaluating the -function is then translated into an \proglang{C++} exception that can be dealt with using -regular \proglang{C++} \code{try}/\code{catch} syntax. - -An open (and rather hard) problem, however, is posed by the fact that calls -into the \proglang{C} API offered by \proglang{R} cannot be reliably protected. Such -calls can always encounter an error condition of their own triggering a call -to \code{Rf_error} which will lead to a sudden death of the program. In -particular, neither \proglang{C++} class destructors nor \code{catch} parts of outer -\code{try}/\code{catch} blocks will be called. This leaves the potential for -memory or resource leakage. So while newly written code can improve on this -situation via use of \proglang{C++} exception handling, existing code calling -into the \proglang{C} API of \proglang{R} cannot be amended just by having an outer layer -of exception handling around it. - - -\section{Performance comparison} -\label{sec:perfcomp} - -In this section, we present several different ways to leverage \pkg{Rcpp} to -rewrite the convolution example from `Writing \proglang{R} Extensions' \citep[Chapter 5]{R:Extensions} -first discussed in Section~\ref{sec:new_rcpp}. -As part of the redesign of \pkg{Rcpp}, data copy is kept to the -absolute minimum: The \code{RObject} class and all its derived -classes are just a container for a \code{SEXP} object. We let \proglang{R} perform -all memory management and access data though the macros or functions -offered by the standard \proglang{R} API. - -The implementation of the \code{operator[]} is designed to be as -efficient as possible, using both inlining and caching, -but even this implementation is still less efficient than the -reference \proglang{C} implementation described in \cite{R:Extensions}. - -\pkg{Rcpp} follows design principles from the STL, and classes such -as \code{NumericVector} expose iterators that can be used for -sequential scans of the data. Algorithms using iterators are -usually more efficient than those that operate on objects using the -\code{operator[]}. The following version of the convolution function -illustrates the use of the \code{NumericVector::iterator}. -% -\begin{Code} -#include - -RcppExport SEXP convolve4cpp(SEXP a, SEXP b) { - Rcpp::NumericVector xa(a), xb(b); - int n_xa = xa.size(), n_xb = xb.size(); - Rcpp::NumericVector xab(n_xa + n_xb - 1); - - typedef Rcpp::NumericVector::iterator vec_iterator; - vec_iterator ia = xa.begin(), ib = xb.begin(); - vec_iterator iab = xab.begin(); - for (int i = 0; i < n_xa; i++) - for (int j = 0; j < n_xb; j++) - iab[i + j] += ia[i] * ib[j]; - - return xab; -} -\end{Code} -% -One of the focuses of recent developments of \pkg{Rcpp} is called `\pkg{Rcpp} sugar', -and aims to provide R-like syntax in \proglang{C++}. While a fuller discussion of \pkg{Rcpp} sugar is -beyond the scope of this article, we have included -another version of the convolution algorithm based on \pkg{Rcpp} sugar for illustrative purposes here: -% -\begin{Code} -#include - -RcppExport SEXP convolve11cpp(SEXP a, SEXP b) { - Rcpp::NumericVector xa(a), xb(b); - int n_xa = xa.size(), n_xb = xb.size(); - Rcpp::NumericVector xab(n_xa + n_xb-1, 0.0); - - Rcpp::Range r( 0, n_xb-1 ); - for (int i=0; i} & 683 & 3.13 \\ - \bottomrule - \end{tabular} - \end{small} - \caption{Run-time performance of the different convolution examples.} - \label{tab:benchmark} - \end{center} -\end{table} - -The first implementation, written in \proglang{C} and using the traditional \proglang{R} API, -provides our base case. It takes advantage of pointer arithmetics and therefore -does not to pay the price of \proglang{C++} object encapsulation or operator overloading. - -The slowest solution illustrates the price of object encapsulation. Calling an overloaded -\code{operator[]} as opposed to using direct pointer arithmetics as in the -reference case costs about 29\% in performance. - -The next implementation uses iterators rather than indexing. Its performance -is indistinguishable from the base case. -This also shows that the use of \proglang{C++} may not necessarily imply any performance -penalty. Further, \proglang{C++} \code{iterators} can be used to achieve the performance -of \proglang{C} pointers, but without the potential dangers of direct memory -access via pointers. - -Finally, the fastest implementation uses \pkg{Rcpp} sugar. It performs -significantly better than the base case. Explicit loop unrolling provides us with -vectorization at the \proglang{C++} level which is responsible for this particular speedup. - -\section{On-going development} -\label{sec:ongoing} - -\pkg{Rcpp} is in very active development: Current work in the -package (and in packages such as \pkg{RcppArmadillo}) -focuses on further improving interoperability between \proglang{R} and \proglang{C++}. -Two core themes for on-going development are `\pkg{Rcpp} sugar' as well as `\pkg{Rcpp} modules', both of which are -also discussed in more detail in specific vignettes in the \pkg{Rcpp} package. - -`\pkg{Rcpp} sugar' offers syntactic -sugar at the \proglang{C++} level, including optimized binary operators and many -\proglang{R} functions such as \code{ifelse}, \code{sapply}, \code{any}, \code{head}, -\code{tail}, and more. -The main technique used in \pkg{Rcpp} sugar is -expression templates pioneered by the \pkg{Blitz++} library \citep{Veldhuizen:1998:Blitz} -and since adopted -by projects such as \pkg{Armadillo} \citep{Sanderson:2010:Armadillo}. -Access to most of the d/p/q/r-variants of the statistical distribution -functions has also been added, enabling the use of expressions such as -\code{dnorm(X, m, s)} for a numeric vector \code{X} and scalars \code{m} and -\code{s}. This was shown in Table~\ref{fig:rnormCode} in -Section~\ref{sec:functions} above where -the \proglang{R} expression \code{rnorm(10L, sd = 100)} -was rewritten in \proglang{C++} as \code{rnorm(10, 0, 100)}. Note that -\proglang{C++} semantics require the second parameter to be used here, which is -different from the \proglang{R} case. - -`\pkg{Rcpp} modules' allows programmers to expose \proglang{C++} functions and classes at the -\proglang{R} level. This offers access to \proglang{C++} code from \proglang{R} using even less interface -code than by writing accessor functions. Modules are inspired by the -\pkg{Boost.Python} library -\citep{Abrahams+Grosse-Kunstleve:2003:Boost.Python} which provides similar -functionality for \proglang{Python}. \proglang{C++} classes exposed by \pkg{Rcpp} modules are -shadowed by reference classes which have been introduced in \proglang{R} 2.12.0. - -\textsl{Update}: Besides the vignettes for '\pkg{Rcpp} Sugar' -\citep{CRAN:Rcpp:Sugar} and '\pkg{Rcpp} Modules' \citep{CRAN:Rcpp:Modules}, -the aforementioned vignette for '\pkg{Rcpp} Attributes' -\citep{CRAN:Rcpp:Attributes} describes a new possibility for even more direct -integration between \proglang{Rcpp} and \proglang{C++}. - -\section{Summary} - -The \pkg{Rcpp} package presented in this paper greatly simplifies integration of -compiled \proglang{C++} code with \proglang{R}. -\pkg{Rcpp} provides a \proglang{C++} class hierarchy which allows manipulation of \proglang{R} data structures in \proglang{C++} -using member functions and operators directly related to the type -of object being used, thereby reducing the level of expertise -required to master the various functions and macros offered by the -internal \proglang{R} API. The classes assume the entire -responsibility of garbage collection of objects, relieving the -programmer from book-keeping operations with the protection stack -and enabling him/her to focus on the underlying problem. - -Data interchange between \proglang{R} and \proglang{C++} code is performed by the \code{wrap()} and -\code{as()} template functions. They allow the programmer to write logic in terms -of \proglang{C++} data structures, and facilitate use of modern libraries such as the -Standard Template Library (STL) and its containers and algorithms. The -\code{wrap()} and \code{as()} template functions are extensible by -design. They are also used either explicitly or implicitly throughout the API. -By using only thin wrappers around \code{SEXP} objects and adopting \proglang{C++} -idioms such as iterators, the footprint of the \pkg{Rcpp} API -is very lightweight, and does not incur a significant performance penalty. - -The \pkg{Rcpp} API offers opportunities to dramatically reduce the complexity -of code, which should lower the initial cost of writing code and improve code readability, maintainability, and -reuse---without incurring noticeable penalties in run-time performance. - -\section*{Acknowledgments} - -Detailed comments and suggestions by editors as well as anonymous referees -are gratefully acknowledged. We are also thankful for code contributions by -Douglas Bates and John Chambers, as well as for very helpful suggestions by Uwe -Ligges, Brian Ripley and Simon Urbanek concerning the build systems for different -platforms. Last but not least, several users provided very fruitful -ideas for new or extended features via the \code{rcpp-devel} mailing list. - -\bibliography{\Sexpr{Rcpp:::bib()}} - -\vspace*{-0.35cm} - -\end{document} - -%%% Local Variables: -%%% mode: latex -%%% TeX-master: t -%%% End: - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-introduction.pdf b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-introduction.pdf deleted file mode 100644 index 9a17f97..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-introduction.pdf and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-modules.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-modules.R deleted file mode 100644 index ecd5676..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-modules.R +++ /dev/null @@ -1,241 +0,0 @@ -### R code from vignette source 'Rcpp-modules.Rnw' - -################################################### -### code chunk number 1: Rcpp-modules.Rnw:38-41 -################################################### -suppressMessages(require(Rcpp)) -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") - - -################################################### -### code chunk number 7: Rcpp-modules.Rnw:212-214 (eval = FALSE) -################################################### -## f1 <- cxxfunction( , "", includes = unifModCode, plugin = "Rcpp" ) -## getDynLib(f1) ## will display information about 'f1' just created - - -################################################### -### code chunk number 8: Rcpp-modules.Rnw:220-239 (eval = FALSE) -################################################### -## setClass( "Uniform", representation( pointer = "externalptr" ) ) -## -## # helper -## Uniform_method <- function(name) { -## paste( "Uniform", name, sep = "__" ) -## } -## -## # syntactic sugar to allow object$method( ... ) -## setMethod( "$", "Uniform", function(x, name ) { -## function(...) .Call( Uniform_method(name) , x@pointer, ... ) -## } ) -## # syntactic sugar to allow new( "Uniform", ... ) -## setMethod( "initialize", "Uniform", function(.Object, ...) { -## .Object@pointer <- .Call( Uniform_method("new"), ... ) -## .Object -## } ) -## -## u <- new( "Uniform", 0, 10 ) -## u$draw( 10L ) - - -################################################### -### code chunk number 10: Rcpp-modules.Rnw:290-304 (eval = FALSE) -################################################### -## inc <- ' -## using namespace Rcpp; -## -## double norm( double x, double y ) { -## return sqrt( x*x + y*y ); -## } -## -## RCPP_MODULE(mod) { -## function( "norm", &norm ); -## } -## ' -## -## fx <- cxxfunction(signature(), plugin="Rcpp", include=inc) -## mod <- Module("mod", getDynLib(fx)) - - -################################################### -### code chunk number 11: Rcpp-modules.Rnw:314-317 (eval = FALSE) -################################################### -## require(nameOfMyModulePackage) -## mod <- new( mod ) -## mod$norm( 3, 4 ) - - -################################################### -### code chunk number 14: Rcpp-modules.Rnw:369-378 (eval = FALSE) -################################################### -## require( Rcpp ) -## -## yd <- Module("yada", getDynLib(fx)) -## yd$bar(2L) -## yd$foo(2L, 10.0) -## yd$hello() -## yd$bla() -## yd$bla1(2L) -## yd$bla2(2L, 5.0) - - -################################################### -### code chunk number 15: Rcpp-modules.Rnw:385-393 (eval = FALSE) -################################################### -## require(myModulePackage) ## or whichever name was chose -## -## bar(2L) -## foo(2L, 10.0) -## hello() -## bla() -## bla1(2L) -## bla2(2L, 5.0) - - -################################################### -### code chunk number 17: Rcpp-modules.Rnw:430-432 (eval = FALSE) -################################################### -## mod <- Module("mod", getDynLib(fx)) -## show(mod$norm) - - -################################################### -### code chunk number 19: Rcpp-modules.Rnw:458-463 (eval = FALSE) -################################################### -## norm <- mod$norm -## norm() -## norm( y = 2 ) -## norm( x = 2, y = 3 ) -## args( norm ) - - -################################################### -### code chunk number 21: Rcpp-modules.Rnw:484-486 (eval = FALSE) -################################################### -## norm <- mod$norm -## args(norm) - - -################################################### -### code chunk number 23: Rcpp-modules.Rnw:505-507 (eval = FALSE) -################################################### -## norm <- mod$norm -## args( norm ) - - -################################################### -### code chunk number 25: Rcpp-modules.Rnw:555-564 (eval = FALSE) -################################################### -## ## assumes fx_unif <- cxxfunction(...) has ben run -## unif_module <- Module( "unif_module", getDynLib(fx_unif ) ) -## Uniform <- unif_module$Uniform -## u <- new( Uniform, 0, 10 ) -## u$draw( 10L ) -## u$range() -## u$max <- 1 -## u$range() -## u$draw( 10 ) - - -################################################### -### code chunk number 35: Rcpp-modules.Rnw:729-735 (eval = FALSE) -################################################### -## Bar <- mod_bar$Bar -## b <- new( Bar, 10 ) -## b$x + b$x -## b$stats() -## b$x <- 10 -## b$stats() - - -################################################### -### code chunk number 38: Rcpp-modules.Rnw:812-816 (eval = FALSE) -################################################### -## setMethod( "show", yada$World , function(object) { -## msg <- paste( "World object with message : ", object$greet() ) -## writeLines( msg ) -## } ) - - -################################################### -### code chunk number 40: Rcpp-modules.Rnw:879-892 (eval = FALSE) -################################################### -## ## for code compiled on the fly using cxxfunction() into 'fx_vec', we use -## mod_vec <- Module( "mod_vec", getDynLib(fx_vec), mustStart = TRUE ) -## vec <- mod_vec$vec -## ## and that is not needed in a package setup as e.g. one created -## ## via Rcpp.package.skeleton(..., module=TRUE) -## v <- new( vec ) -## v$reserve( 50L ) -## v$assign( 1:10 ) -## v$push_back( 10 ) -## v$size() -## v$capacity() -## v[[ 0L ]] -## v$as.vector() - - -################################################### -### code chunk number 41: Rcpp-modules.Rnw:906-907 -################################################### -options( prompt = " ", continue = " " ) - - -################################################### -### code chunk number 42: Rcpp-modules.Rnw:910-911 (eval = FALSE) -################################################### -## import(Rcpp) - - -################################################### -### code chunk number 43: Rcpp-modules.Rnw:916-917 (eval = FALSE) -################################################### -## import(Rcpp, evalCpp) - - -################################################### -### code chunk number 44: Rcpp-modules.Rnw:931-934 (eval = FALSE) -################################################### -## .onLoad <- function(libname, pkgname) { -## loadRcppModules() -## } - - -################################################### -### code chunk number 45: Rcpp-modules.Rnw:962-965 (eval = FALSE) -################################################### -## loadModule("yada") -## loadModule("stdVector") -## loadModule("NumEx") - - -################################################### -### code chunk number 46: Rcpp-modules.Rnw:977-982 (eval = FALSE) -################################################### -## yada <- Module( "yada" ) -## -## .onLoad <- function(libname, pkgname) { -## # placeholder -## } - - -################################################### -### code chunk number 47: Rcpp-modules.Rnw:985-986 -################################################### -options( prompt = "> ", continue = "+ " ) - - -################################################### -### code chunk number 48: Rcpp-modules.Rnw:996-997 (eval = FALSE) -################################################### -## Rcpp.package.skeleton( "testmod", module = TRUE ) - - -################################################### -### code chunk number 49: Rcpp-modules.Rnw:1010-1012 (eval = FALSE) -################################################### -## yada <- Module( "yada" ) -## prompt( yada, "yada-module.Rd" ) - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-modules.Rnw b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-modules.Rnw deleted file mode 100644 index e1999c8..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-modules.Rnw +++ /dev/null @@ -1,1053 +0,0 @@ -% !Rnw driver = highlight::HighlightWeaveLatex() -\documentclass[10pt]{article} -%\VignetteIndexEntry{Rcpp-modules} -%\VignetteEngine{highlight::highlight} -%\VignetteKeywords{Rcpp, module} -%\VignetteDepends{Rcpp} - -\usepackage[USletter]{vmargin} -\setmargrb{0.75in}{0.75in}{0.75in}{0.75in} - -\usepackage{color, alltt} -\usepackage[authoryear,round,longnamesfirst]{natbib} -\usepackage[colorlinks]{hyperref} -\definecolor{link}{rgb}{0,0,0.3} %% next few lines courtesy of RJournal.sty -\hypersetup{ - colorlinks,% - citecolor=link,% - filecolor=link,% - linkcolor=link,% - urlcolor=link -} - -\usepackage{microtype} %% cf http://www.khirevich.com/latex/microtype/ -\usepackage[T1]{fontenc} %% cf http://www.khirevich.com/latex/font/ -\usepackage[bitstream-charter]{mathdesign} %% cf http://www.khirevich.com/latex/font/ - -\newcommand{\code}[1]{\texttt{#1}} -\newcommand{\proglang}[1]{\textsf{#1}} -\newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}} - -%% This corresponds to setting boxes=TRUE for highlight -\newsavebox{\hlbox} -\definecolor{hlBg}{rgb}{0.949019607843137,0.949019607843137,0.949019607843137} -\definecolor{hlBd}{rgb}{0.9,0.9,0.9} % border -\renewenvironment{Hchunk}{\vspace{0.5em}\noindent\begin{lrbox}{\hlbox}\begin{minipage}[b]{.9\textwidth}}% - {\end{minipage}\end{lrbox}\fcolorbox{hlBd}{hlBg}{\usebox{\hlbox}}\vspace{0.5em}} - -<>= -suppressMessages(require(Rcpp)) -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -@ - -\author{Dirk Eddelbuettel \and Romain Fran\c{c}ois} -\title{Exposing \proglang{C++} functions and classes with \pkg{Rcpp} modules} -\date{\pkg{Rcpp} version \Sexpr{prettyVersion} as of \Sexpr{prettyDate}} - -\begin{document} -\maketitle - -\abstract{ - \noindent - This note discusses \textsl{Rcpp modules}. \textsl{Rcpp modules} allow programmers to - expose \proglang{C++} functions and classes to \proglang{R} with relative - ease. \textsl{Rcpp modules} are inspired from the \pkg{Boost.Python} - \proglang{C++} library \citep{Abrahams+Grosse-Kunstleve:2003:Boost.Python} - which provides similar features for \proglang{Python}. -} - -\section{Motivation} - -Exposing \proglang{C++} functionality to \proglang{R} is greatly facilitated -by the \pkg{Rcpp} package and its underlying \proglang{C++} library -\citep{CRAN:Rcpp,JSS:Rcpp}. \pkg{Rcpp} smoothes many of the rough edges in -\proglang{R} and \proglang{C++} integration by replacing the traditional -\proglang{R} Application Programming Interface (API) described in -`\textsl{Writing R Extensions}' \citep{R:Extensions} with a consistent set of \proglang{C++} -classes. The `\textsl{Rcpp-introduction}' vignette \citep{CRAN:Rcpp,JSS:Rcpp} describes the API and -provides an introduction to using \pkg{Rcpp}. - -These \pkg{Rcpp} facilities offer a lot of assistance to the programmer -wishing to interface \proglang{R} and \proglang{C++}. At the same time, these -facilities are limited as they operate on a function-by-function basis. The -programmer has to implement a \code{.Call} compatible function (to -conform to the \proglang{R} API) using classes of the \pkg{Rcpp} API as -described in the next section. - -\subsection{Exposing functions using \pkg{Rcpp}} - -Exposing existing \proglang{C++} functions to \proglang{R} through \pkg{Rcpp} -usually involves several steps. One approach is to write an additional wrapper -function that is responsible for converting input objects to the appropriate -types, calling the actual worker function and converting the results back to -a suitable type that can be returned to \proglang{R} (\texttt{SEXP}). -Consider the \texttt{norm} function below: - -<>= -double norm( double x, double y ) { - return sqrt( x*x + y*y ); -} -@ - -This simple function does not meet the requirements set by the \texttt{.Call} -convention, so it cannot be called directly by \proglang{R}. Exposing the -function involves writing a simple wrapper function -that does match the \texttt{.Call} requirements. \pkg{Rcpp} makes this easy. - -<>= -using namespace Rcpp; -RcppExport SEXP norm_wrapper(SEXP x_, SEXP y_) { - // step 0: convert input to C++ types - double x = as(x_), y = as(y_); - - // step 1: call the underlying C++ function - double res = norm( x, y ); - - // step 2: return the result as a SEXP - return wrap( res ); -} -@ - -Here we use the (templated) \pkg{Rcpp} converter \texttt{as()} which can -transform from a \texttt{SEXP} to a number of different \proglang{C++} and -\pkg{Rcpp} types. The \pkg{Rcpp} function \texttt{wrap()} offers the opposite -functionality and converts many known types to a \texttt{SEXP}. - -This process is simple enough, and is used by a number of CRAN packages. -However, it requires direct involvement from the programmer, which quickly -becomes tiresome when many functions are involved. \textsl{Rcpp modules} -provides a much more elegant and unintrusive way to expose \proglang{C++} -functions such as the \texttt{norm} function shown above to \proglang{R}. - -We should note that \pkg{Rcpp} now has \textsl{Rcpp attributes} which extends -certain aspect of \textsl{Rcpp modules} and makes binding to simple functions -such as this one even easier. With \textsl{Rcpp attribues} we can just write - -<>= -# include - -// [[Rcpp::export]] -double norm(double x, double y) { - return sqrt(x*x + y*y); -} -@ - -See the corresponding vignette \citep{CRAN:Rcpp:Attributes} for details, but -read on for \textsl{Rcpp modules} which contains to provide features not -covered by \textsl{Rcpp attributes}, particularly when it comes to binding -entire C++ classes and more. - -\subsection{Exposing classes using Rcpp} - -Exposing \proglang{C++} classes or structs is even more of a challenge because it -requires writing glue code for each member function that is to be exposed. - -Consider the simple \texttt{Uniform} class below: - -<>= -class Uniform { -public: - Uniform(double min_, double max_) : min(min_), max(max_) {} - - NumericVector draw(int n) { - RNGScope scope; - return runif( n, min, max ); - } - -private: - double min, max; -}; -@ - -To use this class from R, we at least need to expose the constructor and -the \texttt{draw} method. External pointers -\citep{R:Extensions} are the perfect vessel for this, and using the -\texttt{Rcpp:::XPtr} template from \pkg{Rcpp} we can expose the class -with these two functions: - -<>= -using namespace Rcpp; - -/// create an external pointer to a Uniform object -RcppExport SEXP Uniform__new(SEXP min_, SEXP max_) { - // convert inputs to appropriate C++ types - double min = as(min_), max = as(max_); - - // create a pointer to an Uniform object and wrap it - // as an external pointer - Rcpp::XPtr ptr( new Uniform( min, max ), true ); - - // return the external pointer to the R side - return ptr; -} - -/// invoke the draw method -RcppExport SEXP Uniform__draw( SEXP xp, SEXP n_ ) { - // grab the object as a XPtr (smart pointer) to Uniform - Rcpp::XPtr ptr(xp); - - // convert the parameter to int - int n = as(n_); - - // invoke the function - NumericVector res = ptr->draw( n ); - - // return the result to R - return res; -} -@ - -As it is generally a bad idea to expose external pointers `as is', -they usually get wrapped as a slot of an S4 class. - -Using \code{cxxfunction()} from the \pkg{inline} package, we can build this -example on the fly. Suppose the previous example code assigned to a text variable -\texttt{unifModcode}, we could then do - -%% DE 21 Sep 2013: there must a bug somewhere in the vignette processing -%% as the following example produces only empty lines preceded -%% by '+' -- same for 0.10.4 release and current 0.10.5 pre-release -%% hence shortened example to not show code again -<>= -f1 <- cxxfunction( , "", includes = unifModCode, plugin = "Rcpp" ) -getDynLib(f1) ## will display information about 'f1' just created -@ - -The following listing shows some \textsl{manual} wrapping to access the code, -we will see later how this can be automated: - -<>= -setClass( "Uniform", representation( pointer = "externalptr" ) ) - -# helper -Uniform_method <- function(name) { - paste( "Uniform", name, sep = "__" ) -} - -# syntactic sugar to allow object$method( ... ) -setMethod( "$", "Uniform", function(x, name ) { - function(...) .Call( Uniform_method(name) , x@pointer, ... ) -} ) -# syntactic sugar to allow new( "Uniform", ... ) -setMethod( "initialize", "Uniform", function(.Object, ...) { - .Object@pointer <- .Call( Uniform_method("new"), ... ) - .Object -} ) - -u <- new( "Uniform", 0, 10 ) -u$draw( 10L ) -@ - -\pkg{Rcpp} considerably simplifies the code that would -be involved for using external pointers with the traditional \proglang{R} API. -Yet this still involves a lot of mechanical code that quickly -becomes hard to maintain and error prone. -\textsl{Rcpp modules} offer an elegant way to expose the \texttt{Uniform} -class in a way that makes both the internal -\proglang{C++} code and the \proglang{R} code easier. - - - -\section{Rcpp modules} -\label{sec:modules} - -The design of Rcpp modules has been influenced by \proglang{Python} modules which are generated by the -\texttt{Boost.Python} library \citep{Abrahams+Grosse-Kunstleve:2003:Boost.Python}. -Rcpp modules provide a convenient and easy-to-use way -to expose \proglang{C++} functions and classes to \proglang{R}, grouped -together in a single entity. - -A Rcpp module is created in a \texttt{cpp} file using the \texttt{RCPP\_MODULE} -macro, which then provides declarative code of what the module -exposes to \proglang{R}. - -\subsection{Exposing \proglang{C++} functions using Rcpp modules} - -Consider the \texttt{norm} function from the previous section. -We can expose it to \proglang{R} : - -<>= -using namespace Rcpp; - -double norm( double x, double y ) { - return sqrt( x*x + y*y ); -} - -RCPP_MODULE(mod) { - function( "norm", &norm ); -} -@ - -The code creates an Rcpp module called \texttt{mod} -that exposes the \texttt{norm} function. \pkg{Rcpp} automatically -deduces the conversions that are needed for input and output. This alleviates -the need for a wrapper function using either \pkg{Rcpp} or the \proglang{R} API. - -On the \proglang{R} side, the module is retrieved by using the -\code{Module} function from \pkg{Rcpp} - -<>= -inc <- ' -using namespace Rcpp; - -double norm( double x, double y ) { - return sqrt( x*x + y*y ); -} - -RCPP_MODULE(mod) { - function( "norm", &norm ); -} -' - -fx <- cxxfunction(signature(), plugin="Rcpp", include=inc) -mod <- Module("mod", getDynLib(fx)) -@ - -Note that this example assumed that the previous code segment defining the -module was returned by the \code{cxxfunction()} (from the \pkg{inline} -package) as callable R function \code{fx} from which we can extract the -relevant pointer using \code{getDynLib()}. In the case of using Rcpp modules -via a package (which is detailed in Section~\ref{sec:package} below), modules -are actually loaded differently and we would have used - -<>= -require(nameOfMyModulePackage) -mod <- new( mod ) -mod$norm( 3, 4 ) -@ - -where the module is loaded upon startup and we use the constructor -directly. More details on this aspect follow below. - -A module can contain any number of calls to \texttt{function} to register -many internal functions to \proglang{R}. For example, these 6 functions : - -<>= -std::string hello() { - return "hello"; -} - -int bar( int x) { - return x*2; -} - -double foo( int x, double y) { - return x * y; -} - -void bla( ) { - Rprintf( "hello\\n" ); -} - -void bla1( int x) { - Rprintf( "hello (x = %d)\\n", x ); -} - -void bla2( int x, double y) { - Rprintf( "hello (x = %d, y = %5.2f)\\n", x, y ); -} -@ - -can be exposed with the following minimal code: - -<>= -RCPP_MODULE(yada) { - using namespace Rcpp; - - function("hello" , &hello); - function("bar" , &bar ); - function("foo" , &foo ); - function("bla" , &bla ); - function("bla1" , &bla1 ); - function("bla2" , &bla2 ); -} -@ - -which can then be used from \proglang{R}: - -<>= -require( Rcpp ) - -yd <- Module("yada", getDynLib(fx)) -yd$bar(2L) -yd$foo(2L, 10.0) -yd$hello() -yd$bla() -yd$bla1(2L) -yd$bla2(2L, 5.0) -@ - -In the case of a package (as for example the one created by -\code{Rcpp.package.skeleton()} with argument \code{module=TRUE}; more on that -below), we can use - -<>= -require(myModulePackage) ## or whichever name was chose - -bar(2L) -foo(2L, 10.0) -hello() -bla() -bla1(2L) -bla2(2L, 5.0) -@ - - -The requirements for a function to be exposed to \proglang{R} via Rcpp modules -are: -\begin{itemize} -\item The function takes between 0 and 65 parameters. -\item The type of each input parameter must be manageable by the \texttt{Rcpp::as} -template. -\item The return type of the function must be either \texttt{void} or any type that -can be managed by the \texttt{Rcpp::wrap} template. -\item The function name itself has to be unique in the module. - In other words, no two functions with - the same name but different signatures are allowed. C++ allows overloading - functions. This might be added in future versions of modules. -\end{itemize} - -\subsubsection{Documentation for exposed functions using Rcpp modules} - -In addition to the name of the function and the function pointer, it is possible -to pass a short description of the function as the third parameter of \texttt{function}. - -<>= -using namespace Rcpp; - -double norm( double x, double y ) { - return sqrt( x*x + y*y ); -} - -RCPP_MODULE(mod) { - function( "norm", &norm, "Provides a simple vector norm" ); -} -@ - -The description is used when displaying the function to the R prompt: - -<>= -mod <- Module("mod", getDynLib(fx)) -show(mod$norm) -@ - -\subsubsection{Formal arguments specification} - -\texttt{function} also gives the possibility to specify the formal arguments -of the R function that encapsulates the C++ function, by passing -a \texttt{Rcpp::List} after the function pointer. - -<>= -using namespace Rcpp; - -double norm( double x, double y ) { - return sqrt( x*x + y*y ); -} - -RCPP_MODULE(mod_formals) { - function("norm", - &norm, - List::create( _["x"] = 0.0, _["y"] = 0.0 ), - "Provides a simple vector norm"); -} -@ - -A simple usage example is provided below: - -<>= -norm <- mod$norm -norm() -norm( y = 2 ) -norm( x = 2, y = 3 ) -args( norm ) -@ - -To set formal arguments without default values, simply omit the rhs. - -<>= -using namespace Rcpp; - -double norm( double x, double y ) { - return sqrt( x*x + y*y ); -} - -RCPP_MODULE(mod_formals2) { - function("norm", &norm, - List::create( _["x"], _["y"] = 0.0 ), - "Provides a simple vector norm"); -} -@ - -This can be used as follows: - -<>= -norm <- mod$norm -args(norm) -@ - -The ellipsis (\texttt{...}) can be used to denote that additional arguments -are optional; it does not take a default value. - -<>= -using namespace Rcpp; - -double norm( double x, double y ) { - return sqrt( x*x + y*y ); -} - -RCPP_MODULE(mod_formals3) { - function( "norm", &norm, - List::create( _["x"], _["..."] ), - "documentation for norm"); -} -@ -<>= -norm <- mod$norm -args( norm ) -@ - - -\subsection{Exposing \proglang{C++} classes using Rcpp modules} - -Rcpp modules also provide a mechanism for exposing \proglang{C++} classes, based -on the reference classes introduced in R 2.12.0. - -\subsubsection{Initial example} - -A class is exposed using the \texttt{class\_} keyword. The \texttt{Uniform} -class may be exposed to \proglang{R} as follows: - -<>= -using namespace Rcpp; -class Uniform { -public: - Uniform(double min_, double max_) : min(min_), max(max_) {} - - NumericVector draw(int n) const { - RNGScope scope; - return runif( n, min, max ); - } - - double min, max; -}; - -double uniformRange( Uniform* w) { - return w->max - w->min; -} - -RCPP_MODULE(unif_module) { - - class_( "Uniform" ) - - .constructor() - - .field( "min", &Uniform::min ) - .field( "max", &Uniform::max ) - - .method( "draw", &Uniform::draw ) - .method( "range", &uniformRange ) - ; - -} -@ - -<>= -## assumes fx_unif <- cxxfunction(...) has ben run -unif_module <- Module( "unif_module", getDynLib(fx_unif ) ) -Uniform <- unif_module$Uniform -u <- new( Uniform, 0, 10 ) -u$draw( 10L ) -u$range() -u$max <- 1 -u$range() -u$draw( 10 ) -@ - -\texttt{class\_} is templated by the \proglang{C++} class or struct -that is to be exposed to \proglang{R}. -The parameter of the \texttt{class\_} constructor is the name we will -use on the \proglang{R} side. It usually makes sense to use the same name as the class -name. While this is not enforced, it might be useful when exposing a class -generated from a template. - -Then constructors, fields and methods are exposed. - -\subsubsection{Exposing constructors using Rcpp modules} - -Public constructors that take from 0 and 6 parameters can be exposed -to the R level using the \texttt{.constuctor} template method of \texttt{.class\_}. - -Optionally, \texttt{.constructor} can take a description as the first argument. - -<>= - .constructor("sets the min and max value of the distribution") -@ - -Also, the second argument can be a function pointer (called validator) -matching the following type : - -<>= -typedef bool (*ValidConstructor)(SEXP*,int); -@ - -The validator can be used to implement dispatch to the appropriate constructor, -when multiple constructors taking the same number of arguments are exposed. -The default validator always accepts the constructor as valid if it is passed -the appropriate number of arguments. For example, with the call above, the default -validator accepts any call from R with two \texttt{double} arguments (or -arguments that can be cast to \texttt{double}). - -TODO: include validator example here - -\subsubsection{Exposing fields and properties} - -\texttt{class\_} has three ways to expose fields and properties, as -illustrated in the example below : - -<>= -using namespace Rcpp; -class Foo { -public: - Foo(double x_, double y_, double z_ ): - x(x_), y(y_), z(z_) {} - - double x; - double y; - - double get_z() { return z; } - void set_z( double z_ ) { z = z_; } - -private: - double z; -}; - -RCPP_MODULE(mod_foo) { - class_( "Foo" ) - - .constructor() - - .field( "x", &Foo::x ) - .field_readonly( "y", &Foo::y ) - - .property( "z", &Foo::get_z, &Foo::set_z ) - ; -} -@ - -The \texttt{.field} method exposes a public field with read/write access from R. -\texttt{field} accepts an extra parameter to give a short description of the -field: - -<>= - .field( "x", &Foo::x, "documentation for x" ) -@ - -The \texttt{.field\_readonly} exposes a public field with read-only access from R. -It also accepts the description of the field. - -<>= - .field_readonly( "y", &Foo::y, "documentation for y" ) -@ - -The \texttt{.property} method allows indirect access to fields through -a getter and a setter. The setter is optional, and the property is considered -read-only if the setter is not supplied. A description of the property is also -allowed: - -<>= - // with getter and setter - .property( "z", &Foo::get_z, &Foo::set_z, "Documentation for z" ) - - // with only getter - .property( "z", &Foo::get_z, "Documentation for z" ) -@ - -The type of the field (\textbf{T}) is deduced from the return type of the getter, and if a -setter is given its unique parameter should be of the same type. - -Getters can be member functions taking no parameter and returning a \textbf{T} -(for example \texttt{get\_z} above), or -a free function taking a pointer to the exposed -class and returning a \textbf{T}, for example: - -<>= -double z_get( Foo* foo ) { return foo->get_z(); } -@ - -Setters can be either a member function taking a \texttt{T} and returning void, such -as \texttt{set\_z} above, or a free function taking a pointer to the target -class and a \textbf{T} : - -<>= -void z_set( Foo* foo, double z ) { foo->set_z(z); } -@ - -Using properties gives more flexibility in case field access has to be tracked -or has impact on other fields. For example, this class keeps track of how many times -the \texttt{x} field is read and written. - -<>= -class Bar { -public: - - Bar(double x_) : x(x_), nread(0), nwrite(0) {} - - double get_x( ) { - nread++; - return x; - } - - void set_x( double x_) { - nwrite++; - x = x_; - } - - IntegerVector stats() const { - return IntegerVector::create(_["read"] = nread, - _["write"] = nwrite); - } - -private: - double x; - int nread, nwrite; -}; - -RCPP_MODULE(mod_bar) { - class_( "Bar" ) - - .constructor() - - .property( "x", &Bar::get_x, &Bar::set_x ) - .method( "stats", &Bar::stats ) - ; -} -@ - -Here is a simple usage example: - -<>= -Bar <- mod_bar$Bar -b <- new( Bar, 10 ) -b$x + b$x -b$stats() -b$x <- 10 -b$stats() -@ - -\subsubsection{Exposing methods using Rcpp modules} - -\texttt{class\_} has several overloaded and templated \texttt{.method} -functions allowing the programmer to expose a method associated with the class. - -A legitimate method to be exposed by \texttt{.method} can be: -\begin{itemize} -\item A public member function of the class, either const or non const, that -returns void or any type that can be handled by \texttt{Rcpp::wrap}, and that -takes between 0 and 65 parameters whose types can be handled by \texttt{Rcpp::as}. -\item A free function that takes a pointer to the target class as its first -parameter, followed by 0 or more (up to 65) parameters that can be handled by -\texttt{Rcpp::as} and returning a type that can be handled by \texttt{Rcpp::wrap} -or void. -\end{itemize} - -\paragraph{Documenting methods} \texttt{.method} can also include -a short documentation of the method, after the -method (or free function) pointer. - -<>= -.method("stats", &Bar::stats, - "vector indicating the number of times x has been read and written" ) -@ - -TODO: mention overloading, need good example. - - -\paragraph{Const and non-const member functions} - -\texttt{method} is able to expose both \texttt{const} and \texttt{non const} -member functions of a class. There are however situations where -a class defines two versions of the same method, differing only in their -signature by the \texttt{const}-ness. It is for example the case of the -member functions \texttt{back} of the \texttt{std::vector} template from -the STL. - -<>= -reference back ( ); -const_reference back ( ) const; -@ - -To resolve the ambiguity, it is possible to use \texttt{const\_method} -or \texttt{nonconst\_method} instead of \texttt{method} in order -to restrict the candidate methods. - -\paragraph{Special methods} - -\pkg{Rcpp} considers the methods \texttt{[[} and \texttt{[[<-} special, -and promotes them to indexing methods on the \proglang{R} side. - -\subsubsection{Object finalizers} - -The \texttt{.finalizer} member function of \texttt{class\_} can be used to -register a finalizer. A finalizer is a free function that takes a pointer -to the target class and return \texttt{void}. The finalizer is called -before the destructor and so operates on a valid object of the target class. - -It can be used to perform operations, releasing resources, etc ... - -The finalizer is called automatically when the \proglang{R} object that encapsulates -the \proglang{C++} object is garbage collected. - -\subsubsection{S4 dispatch} - -When a \proglang{C++} class is exposed by the \texttt{class\_} template, -a new S4 class is registered as well. The name of the S4 class is -obfuscated in order to avoid name clashes (i.e. two modules exposing the -same class). - -This allows implementation of \proglang{R}-level -(S4) dispatch. For example, one might implement the \texttt{show} -method for \proglang{C++} \texttt{World} objects: - -<>= -setMethod( "show", yada$World , function(object) { - msg <- paste( "World object with message : ", object$greet() ) - writeLines( msg ) -} ) -@ - -TODO: mention R inheritance (John ?) - -\subsubsection{Full example} - -% TODO: maybe replace this by something from wls or RcppModels ? - -The following example illustrates how to use Rcpp modules to expose -the class \texttt{std::vector} from the STL. - -<>= -typedef std::vector vec; // convenience typedef -void vec_assign( vec* obj, Rcpp::NumericVector data ) { // helpers - obj->assign( data.begin(), data.end() ); -} -void vec_insert( vec* obj, int position, Rcpp::NumericVector data) { - vec::iterator it = obj->begin() + position; - obj->insert( it, data.begin(), data.end() ); -} -Rcpp::NumericVector vec_asR( vec* obj ) { return Rcpp::wrap( *obj ); } -void vec_set( vec* obj, int i, double value ) { obj->at( i ) = value; } - -RCPP_MODULE(mod_vec) { - using namespace Rcpp; - - // we expose the class std::vector as "vec" on the R side - class_( "vec") - - // exposing constructors - .constructor() - .constructor() - - // exposing member functions - .method( "size", &vec::size) - .method( "max_size", &vec::max_size) - .method( "resize", &vec::resize) - .method( "capacity", &vec::capacity) - .method( "empty", &vec::empty) - .method( "reserve", &vec::reserve) - .method( "push_back", &vec::push_back ) - .method( "pop_back", &vec::pop_back ) - .method( "clear", &vec::clear ) - - // specifically exposing const member functions - .const_method( "back", &vec::back ) - .const_method( "front", &vec::front ) - .const_method( "at", &vec::at ) - - // exposing free functions taking a std::vector* - // as their first argument - .method( "assign", &vec_assign ) - .method( "insert", &vec_insert ) - .method( "as.vector", &vec_asR ) - - // special methods for indexing - .const_method( "[[", &vec::at ) - .method( "[[<-", &vec_set ) - ; -} -@ - -<>= -## for code compiled on the fly using cxxfunction() into 'fx_vec', we use -mod_vec <- Module( "mod_vec", getDynLib(fx_vec), mustStart = TRUE ) -vec <- mod_vec$vec -## and that is not needed in a package setup as e.g. one created -## via Rcpp.package.skeleton(..., module=TRUE) -v <- new( vec ) -v$reserve( 50L ) -v$assign( 1:10 ) -v$push_back( 10 ) -v$size() -v$capacity() -v[[ 0L ]] -v$as.vector() -@ - -\section{Using modules in other packages} -\label{sec:package} - -\subsection{Namespace import/export} - -\subsubsection{Import all functions and classes} - -When using \pkg{Rcpp} modules in a packages, the client package needs to -import \pkg{Rcpp}'s namespace. This is achieved by adding the -following line to the \texttt{NAMESPACE} file. - -<>= -options( prompt = " ", continue = " " ) -@ - -<>= -import(Rcpp) -@ - -In some case we have found that explicitly naming a symbol can be preferable: - -<>= -import(Rcpp, evalCpp) -@ - -\subsubsection{Load the module} - -\paragraph{Deprecated older method using loadRcppModules} - -Note: This approach is deprecated as of Rcpp 0.12.5, and now triggers a warning -message. Eventually this function will be withdrawn. - -The simplest way to load all functions and classes from a module directly -into a package namespace used to be to use the \code{loadRcppModules} function -within the \code{.onLoad} body. - -<>= -.onLoad <- function(libname, pkgname) { - loadRcppModules() -} -@ - -This will look in the package's DESCRIPTION file for the \texttt{RcppModules} -field, load each declared module and populate their contents into the -package's namespace. For example, both the \pkg{testRcppModule} package -(which is part of large unit test suite for \pkg{Rcpp}) and the package -created via \code{Rcpp.package.skeleton("somename", module=TRUE)} have this -declaration: - -\begin{verbatim} -RcppModules: yada, stdVector, NumEx -\end{verbatim} - -The \code{loadRcppModules} function has a single argument \texttt{direct} -with a default value of \texttt{TRUE}. With this default value, all content -from the module is exposed directly in the package namespace. If set to -\texttt{FALSE}, all content is exposed as components of the module. - -\paragraph{Preferred current method using loadModule} - -Starting with release 0.9.11, an alternative is provided by the -\code{loadModule()} function which takes the module name as an argument. -It can be placed in any \code{.R} file in the package. This is useful as it allows to load -the module from the same file as some auxiliary \proglang{R} functions using the -module. For the example module, the equivalent code to the \code{.onLoad()} -use shown above then becomes - -<>= -loadModule("yada") -loadModule("stdVector") -loadModule("NumEx") -@ - -This feature is also used in the new Rcpp Classes introduced with Rcpp 0.9.11. - -\subsubsection{Just expose the module} - -Alternatively, it is possible to just expose the module to the user of the package, -and let them extract the functions and classes as needed. This uses lazy loading -so that the module is only loaded the first time the user attempts to extract -a function or a class with the dollar extractor. - -<>= -yada <- Module( "yada" ) - -.onLoad <- function(libname, pkgname) { - # placeholder -} -@ - -<>= -options( prompt = "> ", continue = "+ " ) -@ - - -\subsection{Support for modules in skeleton generator} - -The \code{Rcpp.package.skeleton} function has been improved to help -\pkg{Rcpp} modules. When the \texttt{module} argument is set to \texttt{TRUE}, -the skeleton generator installs code that uses a simple module. - -<>= -Rcpp.package.skeleton( "testmod", module = TRUE ) -@ - -Creating a new package using \textsl{Rcpp modules} is easiest via the call to -\code{Rcpp.package.skeleton()} with argument \code{module=TRUE} as a working -package with three example Modules results. - -\subsection{Module documentation} - -\pkg{Rcpp} defines a \code{prompt} method for the -\code{Module} class, allowing generation of a skeleton of an Rd -file containing some information about the module. - -<>= -yada <- Module( "yada" ) -prompt( yada, "yada-module.Rd" ) -@ - -We strongly recommend using a package when working with Modules. But in case a -manually compiled shared library has to loaded, the return argument of the -\texttt{getDynLib()} function can be supplied as the \texttt{PACKAGE} argument to -the \texttt{Module()} function as well. - - -\section{Future extensions} -\label{sec:future} - -\texttt{Boost.Python} has many more features that we would like to port -to Rcpp modules : class inheritance, default arguments, enum -types, ... - -\section{Known shortcomings} -\label{sec:misfeatures} - -There are some things \textsl{Rcpp modules} is not good at: -\begin{itemize} -\item serialization and deserialization of objects: modules are - implemented via an external pointer using a memory location, which is - non-constant and varies between session. Objects have to be re-created, - which is different from the (de-)serialization that R offers. So these - objects cannot be saved from session to session. -\item mulitple inheritance: currently, only simple class structures are - representable via \textsl{Rcpp modules}. -\end{itemize} - -\section{Summary} - -This note introduced \textsl{Rcpp modules} and illustrated how to expose -\proglang{C++} function and classes more easily to \proglang{R}. -We hope that \proglang{R} and \proglang{C++} programmers -find \textsl{Rcpp modules} useful. - -\bibliographystyle{plainnat} -\bibliography{\Sexpr{Rcpp:::bib()}} - -\end{document} - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-modules.pdf b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-modules.pdf deleted file mode 100644 index 8e47e8f..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-modules.pdf and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-package.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-package.R deleted file mode 100644 index 31baf73..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-package.R +++ /dev/null @@ -1,17 +0,0 @@ -### R code from vignette source 'Rcpp-package.Rnw' - -################################################### -### code chunk number 1: version -################################################### -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -require(Rcpp) -require(highlight) - - -################################################### -### code chunk number 2: tree (eval = FALSE) -################################################### -## Rcpp.package.skeleton("mypackage") - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-package.Rnw b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-package.Rnw deleted file mode 100644 index 6087fa0..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-package.Rnw +++ /dev/null @@ -1,476 +0,0 @@ -% !Rnw driver = highlight::HighlightWeaveLatex() -\documentclass[10pt]{article} -%\VignetteIndexEntry{Rcpp-package} -%\VignetteEngine{highlight::highlight} -%\VignetteKeywords{Rcpp, package} -%\VignetteDepends{Rcpp} - -\usepackage[USletter]{vmargin} -\setmargrb{0.75in}{0.75in}{0.75in}{0.75in} -\usepackage{color,alltt} -\usepackage[authoryear,round,longnamesfirst]{natbib} - -\usepackage[colorlinks]{hyperref} -\definecolor{link}{rgb}{0,0,0.3} %% next few lines courtesy of RJournal.sty -\hypersetup{ - colorlinks,% - citecolor=link,% - filecolor=link,% - linkcolor=link,% - urlcolor=link -} - -\usepackage{microtype} %% cf http://www.khirevich.com/latex/microtype/ -\usepackage[T1]{fontenc} %% cf http://www.khirevich.com/latex/font/ -\usepackage[bitstream-charter]{mathdesign} %% cf http://www.khirevich.com/latex/font/ - -\newcommand{\proglang}[1]{\textsf{#1}} -\newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}} -\newcommand{\code}[1]{\texttt{#1}} -\newcommand{\rdoc}[2]{\href{http://www.rdocumentation.org/packages/#1/functions/#2}{\code{#2}}} - -%% This corresponds to setting boxes=TRUE for highlight -\newsavebox{\hlbox} -\definecolor{hlBg}{rgb}{0.949019607843137,0.949019607843137,0.949019607843137} -\definecolor{hlBd}{rgb}{0.9,0.9,0.9} % border -\renewenvironment{Hchunk}{\vspace{0.5em}\noindent\begin{lrbox}{\hlbox}\begin{minipage}[b]{.9\textwidth}}% - {\end{minipage}\end{lrbox}\fcolorbox{hlBd}{hlBg}{\usebox{\hlbox}}\vspace{0.5em}} - -<>= -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -require(Rcpp) -require(highlight) -@ - -\author{Dirk Eddelbuettel \and Romain Fran\c{c}ois} -\title{Writing a package that uses \pkg{Rcpp} } -\date{\pkg{Rcpp} version \Sexpr{prettyVersion} as of \Sexpr{prettyDate}} - - -\begin{document} -\maketitle - -\abstract{ - \noindent This document provides a short overview of how to use - \pkg{Rcpp}~\citep{CRAN:Rcpp,JSS:Rcpp,Eddelbuettel:2013:Rcpp} when writing - an \proglang{R} package. It shows how usage of the function - \rdoc{Rcpp}{Rcpp.package.skeleton} which creates a complete and - self-sufficient example package using \pkg{Rcpp}. All components of the - directory tree created by \rdoc{Rcpp}{Rcpp.package.skeleton} are discussed - in detail. This document thereby complements the \textsl{Writing R - Extensions} manual~\citep{R:Extensions} which is the authoritative source - on how to extend \proglang{R} in general. } - -\section{Introduction} - -\pkg{Rcpp}~\citep{CRAN:Rcpp,JSS:Rcpp,Eddelbuettel:2013:Rcpp} is an extension -package for \proglang{R} which offers an easy-to-use yet featureful interface -between \proglang{C++} and \proglang{R}. However, it is somewhat different -from a traditional \proglang{R} package because its key component is a -\proglang{C++} library. A client package that wants to make use of the -\pkg{Rcpp} features must link against the library provided by \pkg{Rcpp}. - -It should be noted that \proglang{R} has only limited support for -\proglang{C(++)}-level dependencies between packages~\citep{R:Extensions}. The -\texttt{LinkingTo} declaration in the package \texttt{DESCRIPTION} file -allows the client package to retrieve the headers of the target package (here -\pkg{Rcpp}), but support for linking against a library is not provided by -\proglang{R} and has to be added manually. - -This document follows the steps of the \rdoc{Rcpp}{Rcpp.package.skeleton} -function to illustrate a recommended way of using \pkg{Rcpp} from a client -package. We illustrate this using a simple \proglang{C++} function -which will be called by an \proglang{R} function. - -We strongly encourage the reader to become familiar with the material in the -\textsl{Writing R Extensions} manual~\citep{R:Extensions}, as well as with other -documents on \proglang{R} package creation such as \cite{Leisch:2008:Tutorial}. Given -a basic understanding of how to create \proglang{R} package, the present -document aims to provide the additional information on how to use \pkg{Rcpp} -in such add-on packages. - -\section{Using \texttt{Rcpp.package.skeleton}} - -\subsection{Overview} - -\pkg{Rcpp} provides a function \rdoc{Rcpp}{Rcpp.package.skeleton}, modeled -after the base \proglang{R} function \rdoc{utils}{package.skeleton}, which -facilitates creation of a skeleton package using \pkg{Rcpp}. - -\rdoc{Rcpp}{Rcpp.package.skeleton} has a number of arguments documented on -its help page (and similar to those of \rdoc{utils}{package.skeleton}). The -main argument is the first one which provides the name of the package one -aims to create by invoking the function. An illustration of a call using an -argument \texttt{mypackage} is provided below. - -<>= -Rcpp.package.skeleton("mypackage") -@ -\begin{Hchunk} -\begin{verbatim} -$ ls -1R mypackage/ -DESCRIPTION -NAMESPACE -R -Read-and-delete-me -man -src - -mypackage/R: -RcppExports.R - -mypackage/man: -mypackage-package.Rd -rcpp_hello_world.Rd - -mypackage/src: -Makevars ## up until Rcpp 0.10.6, see below -Makevars.win ## up until Rcpp 0.10.6, see below -RcppExports.cpp -rcpp_hello_world.cpp -$ -\end{verbatim} -\end{Hchunk} - -Using \rdoc{Rcpp}{Rcpp.package.skeleton} is by far the simplest approach -as it fulfills two roles. It creates the complete set of files needed for a -package, and it also includes the different components needed for using -\pkg{Rcpp} that we discuss in the following sections. - -\subsection{\proglang{C++} code} - -If the \texttt{attributes} argument is set to -\texttt{TRUE}\footnote{Setting \texttt{attributes} to \texttt{TRUE} is the default. This document -does not cover the behavior of \texttt{Rcpp.package.skeleton} when \texttt{attributes} is set -to \texttt{FALSE} as we try to encourage package developpers to use -attributes. }, -the following \proglang{C++} file is included in the \texttt{src/} directory: - -<>= -#include -using namespace Rcpp; - -// [[Rcpp::export]] -List rcpp_hello_world() { - - CharacterVector x = CharacterVector::create( "foo", "bar" ) ; - NumericVector y = NumericVector::create( 0.0, 1.0 ) ; - List z = List::create( x, y ) ; - - return z ; -} -@ - -The file defines the simple \texttt{rcpp\_hello\_world} function that -uses a few \pkg{Rcpp} classes and returns a \texttt{List}. - -This function is preceded by the \texttt{Rcpp::export} attribute to automatically -handle argument conversion because \proglang{R} has to be taught how to -e.g. handle the \texttt{List} class. - -\rdoc{Rcpp}{Rcpp.package.skeleton} then invokes \rdoc{Rcpp}{compileAttributes} -on the package, which generates the \texttt{RcppExports.cpp} file: - -<>= -// Generated by using Rcpp::compileAttributes() -> do not edit by hand -// Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 - -#include - -using namespace Rcpp; - -// rcpp_hello_world -List rcpp_hello_world(); -RcppExport SEXP mypackage_rcpp_hello_world() { -BEGIN_RCPP - Rcpp::RObject rcpp_result_gen; - Rcpp::RNGScope rcpp_rngScope_gen; - rcpp_result_gen = Rcpp::wrap(rcpp_hello_world()); - return rcpp_result_gen; -END_RCPP -} -@ - -This file defines a function with the appropriate calling convention, suitable for -\rdoc{base}{.Call}. It needs to be regenerated each time functions -exposed by attributes are modified. This is the task of the -\rdoc{Rcpp}{compileAttributes} function. A discussion on attributes is -beyond the scope of this document and more information is available -in the attributes vignette \citep{CRAN:Rcpp:Attributes}. - -\subsection{\proglang{R} code} - -The \rdoc{Rcpp}{compileAttributes} also generates \proglang{R} code -that uses the \proglang{C++} function. - -<>= -# Generated by using Rcpp::compileAttributes() -> do not edit by hand -# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 - -rcpp_hello_world <- function() { - .Call('mypackage_rcpp_hello_world', PACKAGE = 'mypackage') -} -@ - -This is also a generated file so it should not be modified manually, rather -regenerated as needed by \rdoc{Rcpp}{compileAttributes}. - -\subsection{\texttt{DESCRIPTION}} - -The skeleton generates an appropriate \texttt{DESCRIPTION} file, using -both \texttt{Imports:} and \texttt{LinkingTo} for \pkg{Rcpp}: - -\begin{Hchunk} -\begin{verbatim} -Package: mypackage -Type: Package -Title: What the package does (short line) -Version: 1.0 -Date: 2013-09-17 -Author: Who wrote it -Maintainer: Who to complain to -Description: More about what it does (maybe more than one line) -License: What Licence is it under ? -Imports: Rcpp (>= 0.11.0) -LinkingTo: Rcpp -\end{verbatim} -\end{Hchunk} - -\rdoc{Rcpp}{Rcpp.package.skeleton} adds the three last lines to the -\texttt{DESCRIPTION} file generated by \rdoc{utils}{package.skeleton}. - -The \texttt{Imports} declaration indicates \proglang{R}-level dependency -between the client package and \pkg{Rcpp}; code from the latter is being -imported into the package described here. The \texttt{LinkingTo} declaration -indicates that the client package needs to use header files exposed by -\pkg{Rcpp}. - -\subsection{Now optional: \texttt{Makevars} and \texttt{Makevars.win}} - -This behaviour changed with \pkg{Rcpp} release 0.11.0. These files used to be -mandatory, now they are merely optional. - -We will describe the old setting first as it was in use for a few years. The -new standard, however, is much easier and is described below. - -\subsubsection{Releases up until 0.10.6} - -Unfortunately, the \texttt{LinkingTo} declaration in itself was not -enough to link to the user \proglang{C++} library of \pkg{Rcpp}. Until more -explicit support for libraries is added to \proglang{R}, ones needes to manually -add the \pkg{Rcpp} library to the \texttt{PKG\_LIBS} variable in the -\texttt{Makevars} and \texttt{Makevars.win} files. (This has now changed with -release 0.11.0; see below). -\pkg{Rcpp} provides the unexported function \texttt{Rcpp:::LdFlags()} to ease the process: - -\begin{Hchunk} -\begin{verbatim} -## Use the R_HOME indirection to support installations of multiple R version -PKG_LIBS = `$(R_HOME)/bin/Rscript -e "Rcpp:::LdFlags()"` - -## As an alternative, one can also add this code in a file 'configure' -## -## PKG_LIBS=`${R_HOME}/bin/Rscript -e "Rcpp:::LdFlags()"` -## -## sed -e "s|@PKG_LIBS@|${PKG_LIBS}|" \ -## src/Makevars.in > src/Makevars -## -## which together with the following file 'src/Makevars.in' -## -## PKG_LIBS = @PKG_LIBS@ -## -## can be used to create src/Makevars dynamically. This scheme is more -## powerful and can be expanded to also check for and link with other -## libraries. It should be complemented by a file 'cleanup' -## -## rm src/Makevars -## -## which removes the autogenerated file src/Makevars. -## -## Of course, autoconf can also be used to write configure files. This is -## done by a number of packages, but recommended only for more advanced users -## comfortable with autoconf and its related tools. -\end{verbatim} -\end{Hchunk} - - -The \texttt{Makevars.win} is the equivalent, targeting windows. - -\begin{Hchunk} -\begin{verbatim} -## Use the R_HOME indirection to support installations of multiple R version -PKG_LIBS = $(shell "${R_HOME}/bin${R_ARCH_BIN}/Rscript.exe" -e "Rcpp:::LdFlags()") -\end{verbatim} -\end{Hchunk} - -\subsubsection{Releases since 0.11.0} - -As of release 0.11.0, this is no longer needed as client packages obtain the -required code from \pkg{Rcpp} via explicit function registration. The user -does not have to do anything. - -This means that \code{PKG\_LIBS} can now be empty---unless some client -libraries are needed. For example, \pkg{RcppCNPy} needs compression support -and hence uses \code{PKG\_LIBS= -lz}. Similarly, when a third-party library is -required, it can and should be set here. - -\subsection{\texttt{NAMESPACE}} - -The \rdoc{Rcpp}{Rcpp.package.skeleton} function also creates a file -\texttt{NAMESPACE}. - -\begin{Hchunk} -\begin{verbatim} -useDynLib(mypackage) -exportPattern("^[[:alpha:]]+") -importFrom(Rcpp, evalCpp) -\end{verbatim} -\end{Hchunk} - -This file serves three purposes. First, it ensure that the dynamic library -contained in the package we are creating via -\rdoc{Rcpp}{Rcpp.package.skeleton} will be loaded and thereby made -available to the newly created \proglang{R} package. - -Second, it declares which functions should be globally visible from the -namespace of this package. As a reasonable default, we export all functions. - -Third, it instructs R to import a symbol from \pkg{Rcpp}. This sets up the -import of all registered function and, together with the \code{Imports:} -statement in \code{DESCRIPTION}, provides what is needed for client packages -to access \pkg{Rcpp} functionality. - -\subsection{Help files} - -Also created is a directory \texttt{man} containing two help files. One is -for the package itself, the other for the (single) \proglang{R} function -being provided and exported. - -The \textsl{Writing R Extensions} manual~\citep{R:Extensions} provides the complete -documentation on how to create suitable content for help files. - -\subsubsection{\texttt{mypackage-package.Rd}} - -The help file \texttt{mypackage-package.Rd} can be used to describe -the new package. - -\begin{Hchunk} -\begin{verbatim} -\name{mypackage-package} -\alias{mypackage-package} -\alias{mypackage} -\docType{package} -\title{ -What the package does (short line) -} -\description{ -More about what it does (maybe more than one line) -~~ A concise (1-5 lines) description of the package ~~ -} -\details{ -\tabular{ll}{ -Package: \tab mypackage\cr -Type: \tab Package\cr -Version: \tab 1.0\cr -Date: \tab 2013-09-17\cr -License: \tab What license is it under?\cr -} -~~ An overview of how to use the package, including the most important functions ~~ -} -\author{ -Who wrote it - -Maintainer: Who to complain to -} -\references{ -~~ Literature or other references for background information ~~ -} -~~ Optionally other standard keywords, one per line, from file KEYWORDS in the R documentation directory ~~ -\keyword{ package } -\seealso{ -~~ Optional links to other man pages, e.g. ~~ -~~ \code{\link[:-package]{}} ~~ -} -\examples{ -%% ~~ simple examples of the most important functions ~~ -} -\end{verbatim} -\end{Hchunk} - -\subsubsection{\texttt{rcpp\_hello\_world.Rd}} - -The help file \texttt{rcpp\_hello\_world.Rd} serves as documentation for the -example \proglang{R} function. - -\begin{Hchunk} -\begin{verbatim} -\name{rcpp_hello_world} -\alias{rcpp_hello_world} -\docType{package} -\title{ -Simple function using Rcpp -} -\description{ -Simple function using Rcpp -} -\usage{ -rcpp_hello_world() -} -\examples{ -\dontrun{ -rcpp_hello_world() -} -} -\end{verbatim} -\end{Hchunk} - -\section{Using modules} - -This document does not cover the use of the \texttt{module} argument -of \rdoc{Rcpp}{Rcpp.package.skeleton}. It is covered -in the modules vignette \citep{CRAN:Rcpp:Modules}. - -\section{Further examples} - -The canonical example of a package that uses \pkg{Rcpp} is the -\pkg{RcppExamples} \citep{CRAN:RcppExamples} package. \pkg{RcppExamples} -contains various examples of using \pkg{Rcpp}. Hence, the \pkg{RcppExamples} -package is provided as a template for employing \pkg{Rcpp} in packages. - -Other CRAN packages using the \pkg{Rcpp} package are \pkg{RcppArmadillo} -\citep{CRAN:RcppArmadillo}, -and \pkg{minqa} \citep{CRAN:minqa}. Several other packages follow older (but still supported -and appropriate) instructions. They can serve examples on how to get data to -and from \proglang{C++} routines, but should not be considered templates for -how to connect to \pkg{Rcpp}. The full list of packages using \pkg{Rcpp} can -be found at the \href{http://CRAN.R-project.org/package=Rcpp}{CRAN page} of -\pkg{Rcpp}. - -\section{Other compilers} - -Less experienced \proglang{R} users on the Windows platform frequently ask -about using \pkg{Rcpp} with the Visual Studio toolchain. That is simply not -possible as \proglang{R} is built with the \pkg{gcc} compiler. Different -compilers have different linking conventions. These conventions are -particularly hairy when it comes to using \proglang{C++}. In short, it is -not possible to simply drop sources (or header files) from \pkg{Rcpp} into a -\proglang{C++} project built with Visual Studio, and this note makes no -attempt at claiming otherwise. - -\pkg{Rcpp} is fully usable on Windows provided the standard Windows -toolchain for \proglang{R} is used. See the \textsl{Writing R Extensions} -manual~\citep{R:Extensions} for details. - -\section{Summary} - -This document described how to use the \pkg{Rcpp} package for \proglang{R} -and \proglang{C++} integration when writing an \proglang{R} extension -package. The use of the \rdoc{Rcpp}{Rcpp.package.skeleton} was shown in -detail, and references to further examples were provided. - -\bibliographystyle{plainnat} -\bibliography{\Sexpr{Rcpp:::bib()}} - -\end{document} - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-package.pdf b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-package.pdf deleted file mode 100644 index f11a7e0..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-package.pdf and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-quickref.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-quickref.R deleted file mode 100644 index 5c37918..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-quickref.R +++ /dev/null @@ -1,11 +0,0 @@ -### R code from vignette source 'Rcpp-quickref.Rnw' - -################################################### -### code chunk number 1: Rcpp-quickref.Rnw:29-33 -################################################### -options( width= 50) -library( "Rcpp" ) -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-quickref.Rnw b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-quickref.Rnw deleted file mode 100644 index 218d37d..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-quickref.Rnw +++ /dev/null @@ -1,491 +0,0 @@ -% !Rnw driver = highlight::HighlightWeaveLatex() -\documentclass[8pt,twocolumn,a4paper]{article} -%\VignetteIndexEntry{Rcpp-quickref} -%\VignetteEngine{highlight::highlight} -%\VignetteKeywords{Rcpp, reference} -%\VignetteDepends{Rcpp} - -\setlength{\hoffset}{-0.8in} -\setlength{\voffset}{-0.8in} - -\setlength{\marginparwidth}{0pt} -\setlength{\marginparsep}{0pt} -\setlength{\oddsidemargin}{0pt} -\setlength{\headheight}{0pt} -\setlength{\topmargin}{0pt} -\setlength{\headsep}{0pt} -\setlength{\footskip}{0pt} -\setlength{\textheight}{27cm} -\setlength{\textwidth}{20cm} - -\usepackage[colorlinks]{hyperref} - -\usepackage{microtype} %% cf http://www.khirevich.com/latex/microtype/ -\usepackage[T1]{fontenc} %% cf http://www.khirevich.com/latex/font/ -\usepackage[bitstream-charter]{mathdesign} %% cf http://www.khirevich.com/latex/font/ - -\newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}} - -<>= -options( width= 50) -library( "Rcpp" ) -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -@ - -\author{Romain Fran\c{c}ois \and Dirk Eddelbuettel} -\title{\pkg{Rcpp} Quick Reference Guide} -\date{\pkg{Rcpp} version \Sexpr{prettyVersion} as of \Sexpr{prettyDate}} - -\newsavebox{\quickrefbox} -\definecolor{quickrefBg}{rgb}{0.949019607843137,0.949019607843137,0.949019607843137} -\definecolor{quickrefBorder}{rgb}{0,0,0} -\renewenvironment{Hchunk}% -{% -\vspace{0.5em}\noindent\begin{lrbox}{\quickrefbox}% -\begin{minipage}[b]{.42\textwidth}% -}% -{% -\end{minipage}% -\end{lrbox}% -\fcolorbox{quickrefBorder}{quickrefBg}{\usebox{\quickrefbox}}% -\vspace{0.5em}}% - -\begin{document} -\maketitle -\thispagestyle{empty} - -% without the ~, latex does not want to newline -% a newline between paragraph and code disconnects them and can orphan heading - -\paragraph{Important Notes}~ - \newline -<>= -// If you experience compiler errors, please check that you have an appropriate version of g++. See `Rcpp-FAQ' for more information. - -// Many of the examples here imply the following: -#include -using namespace Rcpp; -// The cppFunction will automatically add this. - -// Or, prefix Rcpp objects with the Rcpp namespace e.g.: -Rcpp::NumericVector xx(10); -@ - -\paragraph{Create simple vectors}~ - \newline -<>= -SEXP x; std::vector y(10); - -// from SEXP -NumericVector xx(x); - -// of a given size (filled with 0) -NumericVector xx(10); -// ... with a default for all values -NumericVector xx(10, 2.0); - -// range constructor -NumericVector xx( y.begin(), y.end() ); - -// using create -NumericVector xx = NumericVector::create( - 1.0, 2.0, 3.0, 4.0 ); -NumericVector yy = NumericVector::create( - Named["foo"] = 1.0, - _["bar"] = 2.0 ); // _ short for Named -@ - -\paragraph{Extract and set single elements}~ - \newline -<>= -// extract single values -double x0 = xx[0]; -double x1 = xx(1); - -double y0 = yy["foo"]; -double y1 = yy["bar"]; - -// set single values -xx[0] = 2.1; -xx(1) = 4.2; - -yy["foo"] = 3.0; - -// grow the vector -yy["foobar"] = 10.0; -@ - -\paragraph{Using matrices}~ - \newline -<>= -// Initializing from SEXP, -// dimensions handled automatically -SEXP x; -NumericMatrix xx(x); - -// Matrix of 4 rows & 5 columns (filled with 0) -NumericMatrix xx(4, 5); - -// Fill with value -int xsize = xx.nrow() * xx.ncol(); -for (int i = 0; i < xsize; i++) { - xx[i] = 7; -} -// Same as above, using STL fill -std::fill(xx.begin(), xx.end(), 8); - -// Assign this value to single element -// (1st row, 2nd col) -xx(0,1) = 4; - -// Reference the second column -// Changes propagate to xx (same applies for Row) -NumericMatrix::Column zzcol = xx( _, 1); -zzcol = zzcol * 2; - -// Copy the second column into new object -NumericVector zz1 = xx( _, 1); -// Copy the submatrix (top left 3x3) into new object -NumericMatrix zz2 = xx( Range(0,2), Range(0,2)); -@ - -\paragraph{Inline C++ Compile in R}~ - \newline -<>= -## Note - this is R code. -## cppFunction in Rcpp allows rapid testing. -require(Rcpp) - -cppFunction(" -NumericVector exfun(NumericVector x, int i){ - x = x*i; - return x; -}") - -exfun(1:5, 3) - -## Use evalCpp to evaluate C++ expressions -evalCpp("std::numeric_limits::max()") -@ - -\paragraph{Interface with R}~ - \newline -<>= -## In R, create a package shell. For details, see the "Writing R Extensions" manual. - -Rcpp.package.skeleton("myPackage") - -## Add R code to pkg R/ directory. Call C++ function. Do type-checking in R. - -myfunR = function(Rx, Ry) { - ret = .Call("myCfun", Rx, Ry, - package="myPackage") - return(ret) -} - -// Add C++ code to pkg src/ directory. -using namespace Rcpp; -// Define function as extern with RcppExport -RcppExport SEXP myCfun( SEXP x, SEXP y) { - // If R/C++ types match, use pointer to x. Pointer is faster, but changes to xx propagate to R ( xx -> x == Rx). - NumericVector xx(x); - // clone is slower and uses extra memory. Safe, R-like. - NumericVector yy(clone(y)); - xx[0] = yy[0] = -1.5; - int zz = xx[0]; - // use wrap() to return non-SEXP objects, e.g: - // return(wrap(zz)); - // Build and return a list - List ret; ret["x"] = xx; ret["y"] = yy; - return(ret); -} - -## From shell, above package directory -R CMD check myPackage ## Optional -R CMD INSTALL myPackage - -## In R: -require(myPackage) -aa = 1.5; bb = 1.5; cc = myfunR(aa, bb) -aa == bb ## FALSE, C++ modifies aa -aa = 1:2; bb = 1:2; cc = myfunR(aa, bb) -identical(aa, bb) -## TRUE, R/C++ types don't match -@ - -\paragraph{STL interface}~ - \newline -<>= -// sum a vector from beginning to end -double s = std::accumulate(x.begin(), - x.end(), 0.0); -// prod of elements from beginning to end -int p = std::accumulate(vec.begin(), - vec.end(), 1, std::multiplies()); -// inner_product to compute sum of squares -double s2 = std::inner_product(res.begin(), - res.end(), res.begin(), 0.0); -@ - -\paragraph{Rcpp Attributes}~ - \newline -<>= -// Add code below into C++ file Rcpp_example.cpp - -#include -using namespace Rcpp; - -// Place the export tag right above function declaration. - -// [[Rcpp::export]] -double muRcpp(NumericVector x){ - int n = x.size(); // Size of vector - double sum = 0; // Sum value - - // For loop, note cpp index shift to 0 - for(int i = 0; i < n; i++){ - // Shorthand for sum = sum + x[i] - sum += x[i]; - } - - return sum/n; // Obtain and return the Mean -} - -// Place dependent functions above call or -// declare the function definition with: -double muRcpp(NumericVector x); - -// [[Rcpp::export]] -double varRcpp(NumericVector x, bool bias = true){ - // Calculate the mean using C++ function - double mean = muRcpp(x); - double sum = 0; - int n = x.size(); - - for(int i = 0; i < n; i++){ - sum += pow(x[i] - mean, 2.0); // Square - } - - return sum/(n-bias); // Return variance -} - -## In R: -require(Rcpp) -sourceCpp("path/to/file/Rcpp_example.cpp") -x = 1:5; -all.equal(muRcpp(x), mean(x)); all.equal(var(x),varRcpp(x)) -## TRUE -@ - - - -\paragraph{Rcpp Extensions}~ - \newline -<>= -// Enable C++11 -// [[Rcpp::plugins(cpp11)]] - -// Enable OpenMP (excludes macOS) -// [[Rcpp::plugins(openmp)]] - -// Use the RcppArmadillo package -// Requires different header file from Rcpp.h -#include -// [[Rcpp::depends(RcppArmadillo)]] -@ - - - -\paragraph{Rcpp sugar}~ - \newline -<>= -NumericVector x = NumericVector::create( - -2.0, -1.0, 0.0, 1.0, 2.0 ); -IntegerVector y = IntegerVector::create( - -2, -1, 0, 1, 2 ); - -NumericVector xx = abs( x ); -IntegerVector yy = abs( y ); - -bool b = all( x < 3.0 ).is_true() ; -bool b = any( y > 2 ).is_true(); - -NumericVector xx = ceil( x ); -NumericVector xx = ceiling( x ); -NumericVector yy = floor( y ); -NumericVector yy = floor( y ); - -NumericVector xx = exp( x ); -NumericVector yy = exp( y ); - -NumericVector xx = head( x, 2 ); -IntegerVector yy = head( y, 2 ); - -IntegerVector xx = seq_len( 10 ); -IntegerVector yy = seq_along( y ); - -NumericVector xx = rep( x, 3 ); -NumericVector xx = rep_len( x, 10 ); -NumericVector xx = rep_each( x, 3 ); - -IntegerVector yy = rev( y ); -@ - - - -\paragraph{Random functions}~ - \newline -<>= -// Set seed -RNGScope scope; - -// For details see Section 6.7.1--Distribution functions of the `Writing R Extensions' manual. In some cases (e.g. rnorm), distribution-specific arguments can be omitted; when in doubt, specify all dist-specific arguments. The use of doubles rather than integers for dist-specific arguments is recommended. Unless explicitly specified, log=FALSE. - -// Equivalent to R calls -NumericVector xx = runif(20); -NumericVector xx1 = rnorm(20); -NumericVector xx1 = rnorm(20, 0); -NumericVector xx1 = rnorm(20, 0, 1); - -// Example vector of quantiles -NumericVector quants(5); -for (int i = 0; i < 5; i++) { - quants[i] = (i-2); -} - -// in R, dnorm(-2:2) -NumericVector yy = dnorm(quants) ; -NumericVector yy = dnorm(quants, 0.0, 1.0) ; - -// in R, dnorm(-2:2, mean=2, log=TRUE) -NumericVector yy = dnorm(quants, 2.0, true) ; - -// Note - cannot specify sd without mean -// in R, dnorm(-2:2, mean=0, sd=2, log=TRUE) -NumericVector yy = dnorm(quants, 0.0, 2.0, true) ; - -// To get original R api, use Rf_* -double zz = Rf_rnorm(0, 2); -@ - - - -\newpage - -\paragraph{Environment}~ - \newline -<>= -// Obtain an R environment -Environment stats("package:stats"); -Environment env( 2 ); // by position - -// Special environments -Environment::Rcpp_namespace(); -Environment::base_env(); -Environment::base_namespace(); -Environment::global_env(); -Environment::empty_env(); - -// Extract function from specific -// environment -Function rnorm = stats["rnorm"]; - -// Assign into the environment -glob["x"] = "foo"; -glob["y"] = 3; - -// Retrieve information from environment -std::string x = glob["x"]; -glob.assign( "foo" , 3 ); -int foo = glob.get( "foo" ); -int foo = glob.find( "foo" ); -CharacterVector names = glob.ls() -bool b = glob.exists( "foo" ); -glob.remove( "foo" ); - -// Administration -glob.lockBinding("foo"); -glob.unlockBinding("foo"); -bool b = glob.bindingIsLocked("foo"); -bool b = glob.bindingIsActive("foo"); - -// Retrieve related environments -Environment e = stats.parent(); -Environment e = glob.new_child(); -@ - -\paragraph{Calling Functions in R}~ - \newline -<>= -// Do NOT expect to have a performance gain -// when calling R functions from R! - -// Retrieve functions from default loaded environment -Function rnorm("rnorm"); -rnorm(100, _["mean"] = 10.2, _["sd"] = 3.2 ); - -// Passing in an R function and obtaining results -// Make sure the function conforms with return type! -NumericVector callFunction(NumericVector x, - Function f) { - NumericVector res = f(x); - return res; -} - -## In R: -x = 1:5 -callFunction(x, sum) -@ - -\newpage - -\paragraph{Modules}~ - \newline -<>= -// Warning -- At present, module-based objects do not persist across quit(save="yes")/reload cycles. To be safe, save results to R objects and remove module objects before exiting R. - -// To create a module-containing package from R, use: -Rcpp.package.skeleton("mypackage",module=TRUE) -// You will need to edit the RcppModules: line of the DESCRIPTION file to match your module name (in this example, from yada to mod_bar). - -class Bar { - public: - Bar(double x_) : - x(x_), nread(0), nwrite(0) {} - - double get_x( ) { - nread++; return x; - } - - void set_x( double x_) { - nwrite++; x = x_; - } - - IntegerVector stats() const { - return IntegerVector::create( - _["read"] = nread, - _["write"] = nwrite); - } - private: - double x; int nread, nwrite; -}; - -RCPP_MODULE(mod_bar) { - class_( "Bar" ) - .constructor() - .property( "x", &Bar::get_x, &Bar::set_x, - "Docstring for x" ) - .method( "stats", &Bar::stats, - "Docstring for stats") -;} - -## The following is R code. -require(mypackage); show(Bar) -b <- new(Bar, 10); b$x <- 10 -b_persist <- list(stats=b$stats(), x=b$x) -rm(b) -@ - - -\end{document} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-quickref.pdf b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-quickref.pdf deleted file mode 100644 index 650e952..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-quickref.pdf and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-sugar.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-sugar.R deleted file mode 100644 index 35907a8..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-sugar.R +++ /dev/null @@ -1,17 +0,0 @@ -### R code from vignette source 'Rcpp-sugar.Rnw' - -################################################### -### code chunk number 1: Rcpp-sugar.Rnw:42-44 -################################################### -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") - - -################################################### -### code chunk number 3: Rcpp-sugar.Rnw:105-108 (eval = FALSE) -################################################### -## foo <- function(x, y){ -## ifelse( x < y, x*x, -(y*y) ) -## } - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-sugar.Rnw b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-sugar.Rnw deleted file mode 100644 index db44523..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-sugar.Rnw +++ /dev/null @@ -1,779 +0,0 @@ -% !Rnw driver = highlight::HighlightWeaveLatex() -\documentclass[10pt]{article} -%\VignetteIndexEntry{Rcpp-sugar} -%\VignetteEngine{highlight::highlight} -%\VignetteKeywords{Rcpp, syntactic sugar} -%\VignetteDepends{Rcpp} - -\usepackage[USletter]{vmargin} -\setmargrb{0.75in}{0.75in}{0.75in}{0.75in} - -\usepackage{color, alltt} -\usepackage[authoryear,round,longnamesfirst]{natbib} -\usepackage[colorlinks]{hyperref} -\definecolor{link}{rgb}{0,0,0.3} %% next few lines courtesy of RJournal.sty -\hypersetup{ - colorlinks,% - citecolor=link,% - filecolor=link,% - linkcolor=link,% - urlcolor=link -} - -\usepackage{microtype} %% cf http://www.khirevich.com/latex/microtype/ -\usepackage[T1]{fontenc} %% cf http://www.khirevich.com/latex/font/ -\usepackage[bitstream-charter]{mathdesign} %% cf http://www.khirevich.com/latex/font/ - -\newcommand{\proglang}[1]{\textsf{#1}} -\newcommand{\pkg}[1]{{\fontseries{b}\selectfont #1}} -\newcommand{\sugar}{\textsl{Rcpp sugar}} -\newcommand{\ith}{\textsl{i}-\textsuperscript{th}} -\newcommand{\code}[1]{\texttt{#1}} - - -%% This corresponds to setting boxes=TRUE for highlight -\newsavebox{\hlbox} -\definecolor{hlBg}{rgb}{0.949019607843137,0.949019607843137,0.949019607843137} -\definecolor{hlBd}{rgb}{0.9,0.9,0.9} % border -\renewenvironment{Hchunk}{\vspace{0.5em}\noindent\begin{lrbox}{\hlbox}\begin{minipage}[b]{.9\textwidth}}% - {\end{minipage}\end{lrbox}\fcolorbox{hlBd}{hlBg}{\usebox{\hlbox}}\vspace{0.5em}} - - -<>= -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -@ - -\author{Dirk Eddelbuettel \and Romain Fran\c{c}ois} -\title{\pkg{Rcpp} syntactic sugar} -\date{\pkg{Rcpp} version \Sexpr{prettyVersion} as of \Sexpr{prettyDate}} - -\begin{document} -\maketitle - -\abstract{ - \noindent - This note describes \sugar~which has been introduced in - version 0.8.3 of \pkg{Rcpp} \citep{CRAN:Rcpp,JSS:Rcpp}. \sugar~ - brings a higher-level of abstraction to \proglang{C++} code - written using the \pkg{Rcpp} API. - - \sugar~is based on expression templates - \citep{Abrahams+Gurtovoy:2004:TemplateMetaprogramming,Vandevoorde+Josuttis:2003:Templates} and provides - some 'syntactic sugar' facilities directly in \pkg{Rcpp}. This is similar - to how \pkg{RcppArmadillo} \citep{CRAN:RcppArmadillo} offers - linear algebra \proglang{C++} classes based on \pkg{Armadillo} - \citep{Sanderson:2010:Armadillo}. - % TODO: reference to armadillo, blitz, etc ... -} - -\section{Motivation} - -\pkg{Rcpp} facilitates development of internal compiled code in an \proglang{R} -package by abstracting low-level details of the \proglang{R} API \citep{R:Extensions} -into a consistent set of \proglang{C++} classes. - -Code written using \pkg{Rcpp} classes is easier to read, write and maintain, -without loosing performance. Consider the following code example which -provides a function \texttt{foo} as a \proglang{C++} extension to -\proglang{R} by using the \pkg{Rcpp} API: - -<>= -RcppExport SEXP foo( SEXP x, SEXP y){ - Rcpp::NumericVector xx(x), yy(y) ; - int n = xx.size() ; - Rcpp::NumericVector res( n ) ; - double x_ = 0.0, y_ = 0.0 ; - for( int i=0; i>= -foo <- function(x, y){ - ifelse( x < y, x*x, -(y*y) ) -} -@ - -Put succinctly, the motivation of \sugar~is to bring a subset of the -high-level \proglang{R} syntax in \proglang{C++}. Hence, with \sugar, the -\proglang{C++} version of \texttt{foo} now becomes: - -<>= -RcppExport SEXP foo( SEXP xs, SEXP ys){ - Rcpp::NumericVector x(xs) ; - Rcpp::NumericVector y(ys) ; - return Rcpp::wrap( ifelse( x < y, x*x, -(y*y) )) ; -} -@ - -Apart from the fact that we need to assign the two objects we obtain from -\proglang{R}---which is a simple statement each thanks to the template magic -in \pkg{Rcpp}---and the need for explicit \texttt{return} and -\texttt{Rcpp::wrap} statements, the code is now identical between -highly-vectorised \proglang{R} and \proglang{C++}. - -\sugar~is written using expression templates and lazy evaluation techniques -\citep{Abrahams+Gurtovoy:2004:TemplateMetaprogramming,Vandevoorde+Josuttis:2003:Templates}. -This not only allows a much nicer high-level syntax, but also makes it -rather efficient (as we detail in section~\ref{sec:performance} below). - -\section{Operators} - -\sugar~takes advantage of \proglang{C++} operator overloading. The next few -sections discuss several examples. - -\subsection{Binary arithmetic operators} - -\sugar~defines the usual binary arithmetic operators : \texttt{+}, \texttt{-}, -\texttt{*}, \texttt{/}. - -<>= -// two numeric vectors of the same size -NumericVector x ; -NumericVector y ; - -// expressions involving two vectors -NumericVector res = x + y ; -NumericVector res = x - y ; -NumericVector res = x * y ; -NumericVector res = x / y ; - -// one vector, one single value -NumericVector res = x + 2.0 ; -NumericVector res = 2.0 - x; -NumericVector res = y * 2.0 ; -NumericVector res = 2.0 / y; - -// two expressions -NumericVector res = x * y + y / 2.0 ; -NumericVector res = x * ( y - 2.0 ) ; -NumericVector res = x / ( y * y ) ; -@ - -The left hand side (lhs) and the right hand side (rhs) of each binary -arithmetic expression must be of the same type (for example they should be both -\texttt{numeric} expressions). - -The lhs and the rhs can either have the same size or one of them could -be a primitive value of the appropriate type, for example adding a -\texttt{NumericVector} and a \texttt{double}. - -\subsection{Binary logical operators} - -Binary logical operators create a \texttt{logical} sugar expression -from either two sugar expressions of the same type or one sugar expression -and a primitive value of the associated type. - -<>= -// two integer vectors of the same size -NumericVector x ; -NumericVector y ; - -// expressions involving two vectors -LogicalVector res = x < y ; -LogicalVector res = x > y ; -LogicalVector res = x <= y ; -LogicalVector res = x >= y ; -LogicalVector res = x == y ; -LogicalVector res = x != y ; - -// one vector, one single value -LogicalVector res = x < 2 ; -LogicalVector res = 2 > x; -LogicalVector res = y <= 2 ; -LogicalVector res = 2 != y; - -// two expressions -LogicalVector res = ( x + y ) < ( x*x ) ; -LogicalVector res = ( x + y ) >= ( x*x ) ; -LogicalVector res = ( x + y ) == ( x*x ) ; -@ - -\subsection{Unary operators} - -The unary \texttt{operator-} can be used to negate a (numeric) sugar expression. -whereas the unary \texttt{operator!} negates a logical sugar expression: - -<>= -// a numeric vector -NumericVector x ; - -// negate x -NumericVector res = -x ; - -// use it as part of a numerical expression -NumericVector res = -x * ( x + 2.0 ) ; - -// two integer vectors of the same size -NumericVector y ; -NumericVector z ; - -// negate the logical expression "y < z" -LogicalVector res = ! ( y < z ); -@ - -\section{Functions} - -\sugar~defines functions that closely match the behavior of \proglang{R} -functions of the same name. - -\subsection{Functions producing a single logical result} - -Given a logical sugar expression, the \texttt{all} function identifies if all -the elements are \texttt{TRUE}. Similarly, the \texttt{any} function -identifies if any the element is \texttt{TRUE} when -given a logical sugar expression. - - -<>= -IntegerVector x = seq_len( 1000 ) ; -all( x*x < 3 ) ; -any( x*x < 3 ) ; -@ - -Either call to \texttt{all} and \texttt{any} creates an object of a class -that has member functions \texttt{is\_true}, \texttt{is\_false}, -\texttt{is\_na} and a conversion to \texttt{SEXP} operator. - -One important thing to highlight is that \texttt{all} is lazy. Unlike -\proglang{R}, there is no need to fully evaluate the expression. In the -example above, the result of \texttt{all} is fully resolved after evaluating -only the two first indices of the expression \verb|x * x < 3|. \texttt{any} -is lazy too, so it will only need to resolve the first element of the example -above. - -%\subsubsection{Conversion to bool} - -One important thing to note concernc the conversion to the \texttt{bool} -type. In order to respect the concept of missing values (\texttt{NA}) in -\proglang{R}, expressions generated by \texttt{any} or \texttt{all} can not -be converted to \texttt{bool}. Instead one must use \texttt{is\_true}, -\texttt{is\_false} or \texttt{is\_na}: - -<>= -// wrong: will generate a compile error -bool res = any( x < y) ) ; - -// ok -bool res = is_true( any( x < y ) ) -bool res = is_false( any( x < y ) ) -bool res = is_na( any( x < y ) ) -@ - -% FIXME this may need some expanding the trivariate bool and how to use it - - -\subsection{Functions producing sugar expressions} - -\subsubsection{is\_na} - -Given a sugar expression of any type, \verb|is_na| (just like the other -functions in this section) produces a logical sugar expression of the same -length. Each element of the result expression evaluates to \texttt{TRUE} if -the corresponding input is a missing value, or \texttt{FALSE} otherwise. - -<>= -IntegerVector x = IntegerVector::create( 0, 1, NA_INTEGER, 3 ) ; - -is_na( x ) -all( is_na( x ) ) -any( ! is_na( x ) ) -@ - -\subsubsection{seq\_along} - -Given a sugar expression of any type, \texttt{seq\_along} creates an -integer sugar expression whose values go from 1 to the size of the input. - -<>= -IntegerVector x = IntegerVector::create( 0, 1, NA_INTEGER, 3 ) ; - -seq_along( x ) -seq_along( x * x * x * x * x * x * x ) -@ - -This is the most lazy function, as it only needs to call the \texttt{size} -member function of the input expression. The input expression need not to be -resolved. The two examples above gives the same result with the same efficiency -at runtime. The compile time will be affected by the complexity of the -second expression, since the abstract syntax tree is built at compile time. - -\subsubsection{seq\_len} - -\texttt{seq\_len} creates an integer sugar expression whose \ith\ -element expands to \texttt{i}. \texttt{seq\_len} is particularly useful in -conjunction with \texttt{sapply} and \texttt{lapply}. - -<>= -// 1, 2, ..., 10 -IntegerVector x = seq_len( 10 ) ; - -lapply( seq_len(10), seq_len ) -@ - -\subsubsection{pmin and pmax} - -Given two sugar expressions of the same type and size, or one expression and -one primitive value of the appropriate type, \texttt{pmin} (\texttt{pmax}) -generates a sugar expression of the same type whose \ith\ element expands to -the lowest (highest) value between the \ith\ element of the first expression -and the \ith element of the second expression. - -<>= -IntegerVector x = seq_len( 10 ) ; - -pmin( x, x*x ) -pmin( x*x, 2 ) - -pmin( x, x*x ) -pmin( x*x, 2 ) -@ - -\subsubsection{ifelse} - -Given a logical sugar expression and either : -\begin{itemize} -\item two compatible sugar expression (same type, same size) -\item one sugar expression and one compatible primitive -\end{itemize} -\texttt{ifelse} expands to a sugar expression whose \ith\ -element is the \ith\ element of the first expression -if the \ith\ element of the condition expands to \texttt{TRUE} -or the \ith\ of the second expression if -the \ith\ element of the condition expands to \texttt{FALSE}, -or the appropriate missing value otherwise. - -<>= -IntegerVector x ; -IntegerVector y ; - -ifelse( x < y, x, (x+y)*y ) -ifelse( x > y, x, 2 ) -@ - -\subsubsection{sapply} - -\texttt{sapply} applies a \proglang{C++} function to each element -of the given expression to create a new expression. The type of the -resulting expression is deduced by the compiler from the result type of -the function. - -The function can be a free \proglang{C++} function such as the overload -generated by the template function below: - -<>= -template -T square( const T& x){ - return x * x ; -} -sapply( seq_len(10), square ) ; -@ - -Alternatively, the function can be a functor whose type has a nested type -called \texttt{result\_type} - -<>= -template -struct square : std::unary_function { - T operator()(const T& x){ - return x * x ; - } -} -sapply( seq_len(10), square() ) ; -@ - -\subsubsection{lapply} - -\texttt{lapply} is similar to \texttt{sapply} except that the result is -allways an list expression (an expression of type \texttt{VECSXP}). - -\subsubsection{sign} - -Given a numeric or integer expression, \texttt{sign} expands to an expression -whose values are one of 1, 0, -1 or \texttt{NA}, depending on the sign -of the input expression. - -<>= -IntegerVector xx; - -sign( xx ) -sign( xx * xx ) -@ - -\subsubsection{diff} - -The \ith\ element of the result of \texttt{diff} is -the difference between the $(i+1)$\textsuperscript{th} and the -\ith\ element of the input expression. Supported types are -integer and numeric. - -<>= -IntegerVector xx; - -diff( xx ) -@ - -\subsection{Mathematical functions} - -For the following set of functions, generally speaking, the \ith\ element of -the result of the given function (say, \texttt{abs}) is the result of -applying that function to this \ith\ element of the input expression. -Supported types are integer and numeric. - -<>= -IntegerVector x; - -abs( x ) -exp( x ) -floor( x ) -ceil( x ) -pow(x, z) # x to the power of z -@ - -% log() and log10() maybe? Or ln() ? - -\subsection{The d/q/p/r statistical functions} - -The framework provided by \sugar also permits easy and efficient access the -density, distribution function, quantile and random number generation -functions function by \proglang{R} in the \code{Rmath} library. - -Currently, most of these functions are vectorised for the first element which -denote size. Consequently, these calls works in \proglang{C++} just as they -would in \proglang{R}: - -<>= -x1 = dnorm(y1, 0, 1); // density of y1 at m=0, sd=1 -x2 = qnorm(y2, 0, 1); // quantiles of y2 -x3 = pnorm(y3, 0, 1); // distribution function of y3 -x4 = rnorm(n, 0, 1); // 'n' RNG draws of N(0, 1) -@ - -Similar d/q/p/r functions are provided for the most common distributions: -beta, binom, cauchy, chisq, exp, f, gamma, geom, hyper, lnorm, logis, nbeta, -nbinom, nbinom\_mu, nchisq, nf, norm, nt, pois, t, unif, and weibull. - -Note that the parameterization used in these sugar functions may differ between -the top-level functions exposed in an \proglang{R} session. For example, -the internal \code{rexp} is parameterized by \code{scale}, -whereas the R-level \code{stats::rexp} is parameterized by \code{rate}. -Consult \href{http://cran.r-project.org/doc/manuals/r-release/R-exts.html#Distribution-functions}{Distribution Functions} -for more details on the parameterization used for these sugar functions. - -One point to note is that the programmer using these functions needs to -initialize the state of the random number generator as detailed in Section -6.3 of the `Writing R Extensions' manual \citep{R:Extensions}. A nice -\proglang{C++} solution for this is to use a \textsl{scoped} class that sets -the random number generatator on entry to a block and resets it on exit. We -offer the \code{RNGScope} class which allows code such as - -<>= -RcppExport SEXP getRGamma() { - RNGScope scope; - NumericVector x = rgamma( 10, 1, 1 ); - return x; -} -@ - -As there is some computational overhead involved in using \code{RNGScope}, we -are not wrapping it around each inner function. Rather, the user of these -functions (\textsl{i.e.} you) should place an \code{RNGScope} at the -appropriate level of your code. - - -\section{Performance} -\label{sec:performance} - -TBD - -\section{Implementation} - -This section details some of the techniques used in the implementation of -\sugar. Note that the user need not to be familiar with the implementation -details in order to use \sugar, so this section can be skipped upon a first -read of the paper. - -Writing \sugar~functions is fairly repetitive and follows a well-structured -pattern. So once the basic concepts are mastered (which may take time given -the inherent complexities in template programming), it should be possible to -extend the set of function further following the established pattern.. - -\subsection{The curiously recurring template pattern} - -Expression templates such as those used by \sugar~use a technique -called the \emph{Curiously Recurring Template Pattern} (CRTP). The general -form of CRTP is: - -<>= -// The Curiously Recurring Template Pattern (CRTP) -template -struct base { - // ... -}; -struct derived : base { - // ... -}; -@ - -The \texttt{base} class is templated by the class that derives from it : -\texttt{derived}. This shifts the relationship between a base class and a -derived class as it allows the base class to access methods of the derived -class. - -\subsection{The VectorBase class} - -The CRTP is used as the basis for \sugar~with the \texttt{VectorBase} -class template. All sugar expression derive from one class generated by the -\texttt{VectorBase} template. The current definition of \texttt{VectorBase} -is given here: - -<>= -template -class VectorBase { -public: - struct r_type : traits::integral_constant{} ; - struct can_have_na : traits::integral_constant{} ; - typedef typename traits::storage_type::type stored_type ; - - VECTOR& get_ref(){ - return static_cast(*this) ; - } - - inline stored_type operator[]( int i) const { - return static_cast(this)->operator[](i) ; - } - - inline int size() const { return static_cast(this)->size() ; } - - /* definition ommited here */ - class iterator ; - - inline iterator begin() const { return iterator(*this, 0) ; } - inline iterator end() const { return iterator(*this, size() ) ; } -} -@ - -The \texttt{VectorBase} template has three parameters: - -\begin{itemize} -\item \texttt{RTYPE}: This controls the type of expression (INTSXP, REALSXP, - ...) -\item \texttt{na}: This embeds in the derived type information about whether - instances may contain missing values. \pkg{Rcpp} vector types - (\texttt{IntegerVector}, ...) derive from \texttt{VectorBase} with this - parameter set to \texttt{true} because there is no way to know at - compile-time if the vector will contain missing values at run-time. - However, this parameter is set to \texttt{false} for types that are - generated by sugar expressions as these are guaranteed to produce - expressions that are without missing values. An example is the - \texttt{is\_na} function. This parameter is used in several places as part - of the compile time dispatch to limit the occurence of redundant - operations. -\item \texttt{VECTOR}: This parameter is the key of \sugar. This is the - manifestation of CRTP. The indexing operator and the \texttt{size} method - of \texttt{VectorBase} use a static cast of \texttt{this} to the - \texttt{VECTOR} type to forward calls to the actual method of the derived - class. -\end{itemize} - -\subsection{Example : sapply} - -As an example, the current implementation of \texttt{sapply}, supported by -the template class \texttt{Rcpp::sugar::Sapply} is given below: - -<>= -template -class Sapply : public VectorBase< - Rcpp::traits::r_sexptype_traits< - typename ::Rcpp::traits::result_of::type - >::rtype , - true , - Sapply -> { -public: - typedef typename ::Rcpp::traits::result_of::type ; - const static int RESULT_R_TYPE = - Rcpp::traits::r_sexptype_traits::rtype ; - typedef Rcpp::VectorBase VEC ; - typedef typename Rcpp::traits::r_vector_element_converter::type - converter_type ; - typedef typename Rcpp::traits::storage_type::type STORAGE ; - - Sapply( const VEC& vec_, Function fun_ ) : vec(vec_), fun(fun_){} - - inline STORAGE operator[]( int i ) const { - return converter_type::get( fun( vec[i] ) ); - } - inline int size() const { return vec.size() ; } - -private: - const VEC& vec ; - Function fun ; -} ; - -// sugar - -template -inline sugar::Sapply -sapply( const Rcpp::VectorBase& t, Function fun ){ - return sugar::Sapply( t, fun ) ; -} -@ - -\subsubsection{The sapply function} - -\texttt{sapply} is a template function that takes two arguments. -\begin{itemize} -\item The first argument -is a sugar expression, which we recognize because of the relationship with -the \texttt{VectorBase} class template. -\item The second argument is the function to apply. -\end{itemize} - -The \texttt{sapply} function itself does not do anything, it is just used -to trigger compiler detection of the template parameters that will be used -in the \texttt{sugar::Sapply} template. - -\subsubsection{Detection of return type of the function} - -In order to decide which kind of expression is built, the \texttt{Sapply} -template class queries the template argument via the \texttt{Rcpp::traits::result\_of} -template. - -<>= -typedef typename ::Rcpp::traits::result_of::type result_type ; -@ - -The \texttt{result\_of} type trait is implemented as such: - -<>= -template -struct result_of{ - typedef typename T::result_type type ; -} ; - -template -struct result_of< RESULT_TYPE (*)(INPUT_TYPE) >{ - typedef RESULT_TYPE type ; -} ; -@ - -The generic definition of \texttt{result\_of} targets functors -with a nested \texttt{result\_type} type. - -The second definition is a partial specialization targetting -function pointers. - -\subsubsection{Indentification of expression type} - -Based on the result type of the function, the \texttt{r\_sexptype\_traits} -trait is used to identify the expression type. - -<>= -const static int RESULT_R_TYPE = - Rcpp::traits::r_sexptype_traits::rtype ; -@ - -\subsubsection{Converter} - -The \texttt{r\_vector\_element\_converter} class is used to convert an -object of the function's result type to the actual storage type suitable -for the sugar expression. - -<>= -typedef typename Rcpp::traits::r_vector_element_converter::type - converter_type ; - -@ - -\subsubsection{Storage type} - -The \texttt{storage\_type} trait is used to get access to the storage type -associated with a sugar expression type. For example, the storage type -of a \texttt{REALSXP} expression is \texttt{double}. - -<>= -typedef typename Rcpp::traits::storage_type::type STORAGE ; -@ - -\subsubsection{Input expression base type} - -The input expression --- the expression over which \texttt{sapply} runs --- is -also typedef'ed for convenience: - -<>= -typedef Rcpp::VectorBase VEC ; -@ - -\subsubsection{Output expression base type} - -In order to be part of the \sugar~system, the type generated by the -\texttt{Sapply} class template must inherit from \texttt{VectorBase}. - -<>= -template -class Sapply : public VectorBase< - Rcpp::traits::r_sexptype_traits< - typename ::Rcpp::traits::result_of::type - >::rtype , - true , - Sapply -> -@ - -The expression built by \texttt{Sapply} depends on the result type -of the function, may contain missing values, and the third argument -is the manifestation of the \emph{CRTP}. - -\subsubsection{Constructor} - -The constructor of the \texttt{Sapply} class template is straightforward, it -simply consists of holding the reference to the input expression and the -function. - -<>= -Sapply( const VEC& vec_, Function fun_ ) : vec(vec_), fun(fun_){} - -private: - const VEC& vec ; - Function fun ; -@ - -\subsubsection{Implementation} - -The indexing operator and the \texttt{size} member function is what -the \texttt{VectorBase} expects. The size of the result expression is -the same as the size of the input expression and the i\textsuperscript{th} -element of the result is simply retrieved by applying the function -and the converter. Both these methods are inline to maximize performance: - -<>= -inline STORAGE operator[]( int i ) const { - return converter_type::get( fun( vec[i] ) ); -} -inline int size() const { return vec.size() ; } -@ - -\section{Summary} - -TBD - -\bibliographystyle{plainnat} -\bibliography{\Sexpr{Rcpp:::bib()}} - -\end{document} - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-sugar.pdf b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-sugar.pdf deleted file mode 100644 index cef908f..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-sugar.pdf and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-unitTests.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-unitTests.R deleted file mode 100644 index 6be3695..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-unitTests.R +++ /dev/null @@ -1,56 +0,0 @@ -### R code from vignette source 'Rcpp-unitTests.Rnw' - -################################################### -### code chunk number 1: Rcpp-unitTests.Rnw:14-18 -################################################### -require(Rcpp) -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -library(RUnit) - - -################################################### -### code chunk number 2: unitTesting -################################################### -pkg <- "Rcpp" - -if( Sys.getenv( "TRAVIS" ) == "true" ){ - writeLines( "not running any tests as part of checking the vignette when doing continuous integration with travis" ) -} else { - - ## Check the environemnt variable to see if all tests should be run - if (Sys.getenv("RunAllRcppTests") != "yes") { - writeLines("The environment variable 'RunAllRcppTests' was not set to 'yes', so skipping some tests.") - } - - if (file.exists("unitTests-results")) unlink("unitTests-results", recursive = TRUE) - dir.create("unitTests-results") - path <- system.file("unitTests", package=pkg) - testSuite <- defineTestSuite(name=paste(pkg, "unit testing"), dirs=path) - tests <- runTestSuite(testSuite) - err <- getErrors(tests) - if (err$nFail > 0) stop(sprintf("unit test problems: %d failures", err$nFail)) - if (err$nErr > 0) stop( sprintf("unit test problems: %d errors", err$nErr)) - printHTMLProtocol(tests, fileName=sprintf("unitTests-results/%s-unitTests.html", pkg)) - printTextProtocol(tests, fileName=sprintf("unitTests-results/%s-unitTests.txt" , pkg)) - - #if (file.exists("/tmp")) { - # invisible(sapply(c("txt", "html"), function(ext) { - # fname <- sprintf("unitTests-results/%s-unitTests.%s", pkg, ext) - # file.copy(fname, "/tmp", overwrite=TRUE) - # })) - #} -} - - -################################################### -### code chunk number 3: importResults -################################################### -results <- "unitTests-results/Rcpp-unitTests.txt" -if (file.exists(results)) { - writeLines(readLines(results)) -} else{ - writeLines("Unit test results not available") -} - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-unitTests.Rnw b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-unitTests.Rnw deleted file mode 100644 index 74d53d7..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-unitTests.Rnw +++ /dev/null @@ -1,77 +0,0 @@ -\documentclass[10pt]{article} -%\VignetteIndexEntry{Rcpp-unitTests} -%\VignetteKeywords{R,Rcpp,unit tests} -%\VignetteDepends{Rcpp} -\SweaveOpts{concordance=FALSE} - -\usepackage{vmargin} -\setmargrb{0.75in}{0.75in}{0.75in}{0.75in} - -\usepackage{microtype} %% cf http://www.khirevich.com/latex/microtype/ -\usepackage[T1]{fontenc} %% cf http://www.khirevich.com/latex/font/ -\usepackage[bitstream-charter]{mathdesign} %% cf http://www.khirevich.com/latex/font/ - -<>= -require(Rcpp) -prettyVersion <- packageDescription("Rcpp")$Version -prettyDate <- format(Sys.Date(), "%B %e, %Y") -library(RUnit) -@ - -\usepackage[colorlinks]{hyperref} -\author{Dirk Eddelbuettel \and Romain Fran\c{c}ois} -\title{\textbf{Rcpp}: Unit testing results} -\date{Rcpp version \Sexpr{prettyVersion} as of \Sexpr{prettyDate}} - -\begin{document} -\maketitle - -\section*{Test Execution} - -<>= -pkg <- "Rcpp" - -if( Sys.getenv( "TRAVIS" ) == "true" ){ - writeLines( "not running any tests as part of checking the vignette when doing continuous integration with travis" ) -} else { - - ## Check the environemnt variable to see if all tests should be run - if (Sys.getenv("RunAllRcppTests") != "yes") { - writeLines("The environment variable 'RunAllRcppTests' was not set to 'yes', so skipping some tests.") - } - - if (file.exists("unitTests-results")) unlink("unitTests-results", recursive = TRUE) - dir.create("unitTests-results") - path <- system.file("unitTests", package=pkg) - testSuite <- defineTestSuite(name=paste(pkg, "unit testing"), dirs=path) - tests <- runTestSuite(testSuite) - err <- getErrors(tests) - if (err$nFail > 0) stop(sprintf("unit test problems: %d failures", err$nFail)) - if (err$nErr > 0) stop( sprintf("unit test problems: %d errors", err$nErr)) - printHTMLProtocol(tests, fileName=sprintf("unitTests-results/%s-unitTests.html", pkg)) - printTextProtocol(tests, fileName=sprintf("unitTests-results/%s-unitTests.txt" , pkg)) - - #if (file.exists("/tmp")) { - # invisible(sapply(c("txt", "html"), function(ext) { - # fname <- sprintf("unitTests-results/%s-unitTests.%s", pkg, ext) - # file.copy(fname, "/tmp", overwrite=TRUE) - # })) - #} -} -@ - -\section*{Test Results} - -\begin{verbatim} -<>= -results <- "unitTests-results/Rcpp-unitTests.txt" -if (file.exists(results)) { - writeLines(readLines(results)) -} else{ - writeLines("Unit test results not available") -} -@ - -\end{verbatim} - -\end{document} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-unitTests.pdf b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-unitTests.pdf deleted file mode 100644 index cd127cc..0000000 Binary files a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/Rcpp-unitTests.pdf and /dev/null differ diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/index.html b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/index.html deleted file mode 100644 index b5c82ed..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/doc/index.html +++ /dev/null @@ -1,68 +0,0 @@ - - -R: Vignettes and other documentation - - - -

Vignettes and other documentation - -

-
-
-[Top] -
-

Vignettes from package 'Rcpp'

- ------- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Rcpp::Rcpp-attributesRcpp-attributesPDFsourceR code
Rcpp::Rcpp-extendingRcpp-extendingPDFsourceR code
Rcpp::Rcpp-FAQRcpp-FAQPDFsourceR code
Rcpp::Rcpp-modulesRcpp-modulesPDFsourceR code
Rcpp::Rcpp-packageRcpp-packagePDFsourceR code
Rcpp::Rcpp-quickrefRcpp-quickrefPDFsourceR code
Rcpp::Rcpp-sugarRcpp-sugarPDFsourceR code
Rcpp::Rcpp-introductionRcpp-introductionPDFsourceR code
Rcpp::Rcpp-unitTestsRcpp-unitTestsPDFsourceR code
- diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/Depends.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/Depends.cpp deleted file mode 100644 index 228b4e3..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/Depends.cpp +++ /dev/null @@ -1,28 +0,0 @@ - -// [[Rcpp::depends(RcppArmadillo)]] - -#include - -using namespace Rcpp; - -// [[Rcpp::export]] -List fastLm(NumericVector yr, NumericMatrix Xr) { - - int n = Xr.nrow(), k = Xr.ncol(); - - arma::mat X(Xr.begin(), n, k, false); // reuses memory and avoids extra copy - arma::colvec y(yr.begin(), yr.size(), false); - - arma::colvec coef = arma::solve(X, y); // fit model y ~ X - arma::colvec resid = y - X*coef; // residuals - - double sig2 = arma::as_scalar( arma::trans(resid)*resid/(n-k) ); - // std.error of estimate - arma::colvec stderrest = arma::sqrt( - sig2 * arma::diagvec( arma::inv(arma::trans(X)*X)) ); - - return List::create(Named("coefficients") = coef, - Named("stderr") = stderrest - ); -} - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/Export.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/Export.cpp deleted file mode 100644 index 7252630..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/Export.cpp +++ /dev/null @@ -1,40 +0,0 @@ - -#include - -using namespace Rcpp; - -// [[Rcpp::export]] -int fibonacci(const int x) { - - if (x == 0) return(0); - if (x == 1) return(1); - - return (fibonacci(x - 1)) + fibonacci(x - 2); -} - - -// [[Rcpp::export("convolveCpp")]] -NumericVector convolve(NumericVector a, NumericVector b) { - - int na = a.size(), nb = b.size(); - int nab = na + nb - 1; - NumericVector xab(nab); - - for (int i = 0; i < na; i++) - for (int j = 0; j < nb; j++) - xab[i + j] += a[i] * b[j]; - - return xab; -} - - -// [[Rcpp::export]] -List lapplyCpp(List input, Function f) { - - List output(input.size()); - - std::transform(input.begin(), input.end(), output.begin(), f); - output.names() = input.names(); - - return output; -} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/cppFunction.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/cppFunction.R deleted file mode 100644 index 15d13b4..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/cppFunction.R +++ /dev/null @@ -1,43 +0,0 @@ - -library(Rcpp) - -cppFunction(' - NumericVector convolveCpp(NumericVector a, NumericVector b) { - - int na = a.size(), nb = b.size(); - int nab = na + nb - 1; - NumericVector xab(nab); - - for (int i = 0; i < na; i++) - for (int j = 0; j < nb; j++) - xab[i + j] += a[i] * b[j]; - - return xab; - } -') - -convolveCpp(c(1,2,3), matrix(3,3)) - - -cppFunction(depends='RcppArmadillo', code=' - List fastLm(NumericVector yr, NumericMatrix Xr) { - - int n = Xr.nrow(), k = Xr.ncol(); - - arma::mat X(Xr.begin(), n, k, false); // reuses memory and avoids copy - arma::colvec y(yr.begin(), yr.size(), false); - - arma::colvec coef = arma::solve(X, y); // fit model y ~ X - arma::colvec resid = y - X*coef; // residuals - - double sig2 = arma::as_scalar( arma::trans(resid)*resid/(n-k) ); - // std.error of estimate - arma::colvec stderrest = arma::sqrt( - sig2 * arma::diagvec( arma::inv(arma::trans(X)*X)) ); - - return List::create(Named("coefficients") = coef, - Named("stderr") = stderrest - ); -} -') - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/sourceCpp.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/sourceCpp.R deleted file mode 100644 index ec25c17..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Attributes/sourceCpp.R +++ /dev/null @@ -1,10 +0,0 @@ - -library(Rcpp) - -sourceCpp("Export.cpp") -fibonacci(5) - - -sourceCpp("Depends.cpp") -fastLm(c(1,2,3), matrix(3,3)) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/GNUmakefile b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/GNUmakefile deleted file mode 100644 index 9033f4e..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/GNUmakefile +++ /dev/null @@ -1,29 +0,0 @@ - -## comment this out if you need a different version of R, -## and set set R_HOME accordingly as an environment variable -R_HOME := $(shell R RHOME) - -## include headers and libraries for R -RCPPFLAGS := $(shell $(R_HOME)/bin/R CMD config --cppflags) -RLDFLAGS := $(shell $(R_HOME)/bin/R CMD config --ldflags) - -## include headers and libraries for Rcpp interface classes -RCPPINCL := $(shell echo 'Rcpp:::CxxFlags()' | $(R_HOME)/bin/R --vanilla --slave) -RCPPLIBS := $(shell echo 'Rcpp:::LdFlags()' | $(R_HOME)/bin/R --vanilla --slave) - -c_sources := $(wildcard *.c) -c_sharedlibs := $(patsubst %.c,%.o,$(c_sources)) - -cpp_sources := $(wildcard *.cpp) -cpp_sharedlibs := $(patsubst %.cpp,%.o,$(cpp_sources)) - -all : $(c_sharedlibs) $(cpp_sharedlibs) - -%.o : %.c - R CMD SHLIB $< - -%.o : %.cpp - PKG_CPPFLAGS="$(RCPPFLAGS) $(RCPPINCL)" PKG_LIBS="$(RLDFLAGS) $(RCPPLIBS)" R CMD SHLIB $< - -run : $(c_sharedlibs) $(cpp_sharedlibs) - Rscript exampleRCode.r diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/buildAndRun.sh b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/buildAndRun.sh deleted file mode 100755 index 473c49a..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/buildAndRun.sh +++ /dev/null @@ -1,25 +0,0 @@ -#!/bin/bash - -rm -f *.o *.so - -# build the shared library for the C variant -R CMD SHLIB convolve2_c.c -R CMD SHLIB convolve7_c.c - -# build the shared library for the C++ variant -# we have to let R know where the Rcpp header and library are -export PKG_CPPFLAGS=`Rscript -e "Rcpp:::CxxFlags()"` -export PKG_LIBS=`Rscript -e "Rcpp:::LdFlags()"` -R CMD SHLIB convolve3_cpp.cpp -R CMD SHLIB convolve4_cpp.cpp -R CMD SHLIB convolve5_cpp.cpp -R CMD SHLIB convolve8_cpp.cpp -R CMD SHLIB convolve9_cpp.cpp -R CMD SHLIB convolve10_cpp.cpp -R CMD SHLIB convolve11_cpp.cpp -R CMD SHLIB convolve12_cpp.cpp -R CMD SHLIB convolve14_cpp.cpp - -# call R so that we get an interactive session -Rscript exampleRCode.r - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve10_cpp.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve10_cpp.cpp deleted file mode 100644 index d21b4f0..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve10_cpp.cpp +++ /dev/null @@ -1,36 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- - -// this version expands convolve8_cpp by making Vec mimic the structure of -// NumericVector. It peforms well, so this is is not the structure of -// NumericVector that is the problem. So what is it then ? -// -// could it be because NumericVector is in a different library than -// this code, so that operator[] is not inlined ? -// -// clues: -// - http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka3538.html - -#include - -#include "convolve10_cpp.h" - -RcppExport SEXP convolve10cpp(SEXP a, SEXP b){ - Rcpp::NumericVector xa(a); - Rcpp::NumericVector xb(b); - int n_xa = xa.size() ; - int n_xb = xb.size() ; - int nab = n_xa + n_xb - 1; - Rcpp::NumericVector xab(nab); - - Vec vab(xab.begin()), va(xa.begin()), vb(xb.begin()) ; - - for (int i = 0; i < n_xa; i++) - for (int j = 0; j < n_xb; j++) - vab[i + j] += va[i] * vb[j]; - - return xab ; -} - -#include "loopmacro.h" -LOOPMACRO_CPP(convolve10cpp) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve10_cpp.h b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve10_cpp.h deleted file mode 100644 index 53f93bd..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve10_cpp.h +++ /dev/null @@ -1,27 +0,0 @@ - -class Cache{ -public: - typedef double& proxy ; - typedef double* iterator ; - - Cache( iterator data_) : data(data_){} - - inline proxy ref(int i){ return data[i] ; } - inline proxy ref(int i) const { return data[i] ; } - -private: - iterator data ; -} ; - -class Vec { -public: - typedef double& proxy ; - - Vec( double* data_ ) : cache(data_){} - inline proxy operator[]( int i){ return cache.ref(i) ; } - inline proxy operator[]( int i) const { return cache.ref(i) ; } - -private: - Cache cache ; -} ; - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve11_cpp.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve11_cpp.cpp deleted file mode 100644 index b1f39da..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve11_cpp.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- - -// This version uses nona to indicate that xb does not contain any missing -// value. This is the assumption that all other versions do. - -#include -using namespace Rcpp ; - - -RcppExport SEXP convolve11cpp(SEXP a, SEXP b) { - NumericVector xa(a); int n_xa = xa.size() ; - NumericVector xb(b); int n_xb = xb.size() ; - NumericVector xab(n_xa + n_xb - 1,0.0); - - Range r( 0, n_xb-1 ); - for(int i=0; i - -RcppExport SEXP convolve12cpp(SEXP a, SEXP b){ - Rcpp::NumericVector xa(a), xb(b); - int n_xa = xa.size(), n_xb = xb.size(); - Rcpp::NumericVector xab(n_xa + n_xb - 1); - - typedef Rcpp::NumericVector::iterator vec_iterator ; - vec_iterator ia = xa.begin(), ib = xb.begin(); - vec_iterator iab = xab.begin(); - for (int i = 0; i < n_xa; i++) - for (int j = 0; j < n_xb; j++) - iab[i + j] += ia[i] * ib[j]; - - return xab; -} - -#include "loopmacro.h" -LOOPMACRO_CPP(convolve12cpp) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve13_cpp.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve13_cpp.cpp deleted file mode 100644 index cff5bc8..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve13_cpp.cpp +++ /dev/null @@ -1,27 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- - -// This is a rewrite of the 'Writing R Extensions' section 5.10.1 example - -#include - -template -T convolve( const T& a, const T& b ){ - int na = a.size() ; int nb = b.size() ; - T out(na + nb - 1); - typename T::iterator iter_a(a.begin()), iter_b(b.begin()), iter_ab( out.begin() ) ; - - for (int i = 0; i < na; i++) - for (int j = 0; j < nb; j++) - iter_ab[i + j] += iter_a[i] * iter_b[j]; - - return out ; -} - - -RcppExport SEXP convolve13cpp(SEXP a, SEXP b){ - return convolve( Rcpp::NumericVector(a), Rcpp::NumericVector(b) ) ; -} - -#include "loopmacro.h" -LOOPMACRO_CPP(convolve13cpp) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve14_cpp.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve14_cpp.cpp deleted file mode 100644 index 0c74ff6..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve14_cpp.cpp +++ /dev/null @@ -1,25 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- - -// This is a rewrite of the 'Writing R Extensions' section 5.10.1 example - -#include - -using namespace Rcpp ; -RcppExport SEXP convolve14cpp(SEXP a, SEXP b){ - NumericVector xa(a), xb(b); - int n_xa = xa.size() ; - int n_xb = xb.size() ; - int nab = n_xa + n_xb - 1; - NumericVector xab(nab); - Fast fa(xa), fb(xb), fab(xab) ; - - for (int i = 0; i < n_xa; i++) - for (int j = 0; j < n_xb; j++) - fab[i + j] += fa[i] * fb[j]; - - return xab ; -} - -#include "loopmacro.h" -LOOPMACRO_CPP(convolve14cpp) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve2_c.c b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve2_c.c deleted file mode 100644 index 5d84038..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve2_c.c +++ /dev/null @@ -1,28 +0,0 @@ - -/* This is from 'Writing R Extensions' section 5.10.1 */ - -#include -#include - -SEXP convolve2(SEXP a, SEXP b) -{ - int i, j, na, nb, nab; - double *xa, *xb, *xab; - SEXP ab; - - PROTECT(a = AS_NUMERIC(a)); - PROTECT(b = AS_NUMERIC(b)); - na = LENGTH(a); nb = LENGTH(b); nab = na + nb - 1; - PROTECT(ab = NEW_NUMERIC(nab)); - xa = NUMERIC_POINTER(a); xb = NUMERIC_POINTER(b); - xab = NUMERIC_POINTER(ab); - for(i = 0; i < nab; i++) xab[i] = 0.0; - for(i = 0; i < na; i++) - for(j = 0; j < nb; j++) xab[i + j] += xa[i] * xb[j]; - UNPROTECT(3); - return(ab); -} - -#include "loopmacro.h" -LOOPMACRO_C(convolve2) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve3_cpp.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve3_cpp.cpp deleted file mode 100644 index 173d921..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve3_cpp.cpp +++ /dev/null @@ -1,24 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- - -// This is a rewrite of the 'Writing R Extensions' section 5.10.1 example - -#include - -RcppExport SEXP convolve3cpp(SEXP a, SEXP b){ - Rcpp::NumericVector xa(a); - Rcpp::NumericVector xb(b); - int n_xa = xa.size() ; - int n_xb = xb.size() ; - int nab = n_xa + n_xb - 1; - Rcpp::NumericVector xab(nab); - - for (int i = 0; i < n_xa; i++) - for (int j = 0; j < n_xb; j++) - xab[i + j] += xa[i] * xb[j]; - - return xab ; -} - -#include "loopmacro.h" -LOOPMACRO_CPP(convolve3cpp) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve4_cpp.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve4_cpp.cpp deleted file mode 100644 index b853fff..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve4_cpp.cpp +++ /dev/null @@ -1,29 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- - -// This is a rewrite of the 'Writing R Extensions' section 5.10.1 example - -#include - -RcppExport SEXP convolve4cpp(SEXP a, SEXP b) { - Rcpp::NumericVector xa(a); - Rcpp::NumericVector xb(b); - int n_xa = xa.size() ; - int n_xb = xb.size() ; - int nab = n_xa + n_xb - 1; - Rcpp::NumericVector xab(nab,0.0); - - double* pa = xa.begin() ; - double* pb = xb.begin() ; - double* pab = xab.begin() ; - int i,j=0; - for (i = 0; i < n_xa; i++) - for (j = 0; j < n_xb; j++) - pab[i + j] += pa[i] * pb[j]; - - return xab ; -} - -#include "loopmacro.h" -LOOPMACRO_CPP(convolve4cpp) - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve5_cpp.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve5_cpp.cpp deleted file mode 100644 index 6499ac6..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve5_cpp.cpp +++ /dev/null @@ -1,23 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- - -// This is a rewrite of the 'Writing R Extensions' section 5.10.1 example - -#include -using namespace Rcpp ; - - -RcppExport SEXP convolve5cpp(SEXP a, SEXP b) { - NumericVector xa(a); int n_xa = xa.size() ; - NumericVector xb(b); int n_xb = xb.size() ; - NumericVector xab(n_xa + n_xb - 1,0.0); - - Range r( 0, n_xb-1 ); - for(int i=0; i -#include - -SEXP convolve7(SEXP a, SEXP b) -{ - int i, j, na, nb, nab; - SEXP ab; - - PROTECT(a = AS_NUMERIC(a)); - PROTECT(b = AS_NUMERIC(b)); - na = LENGTH(a); nb = LENGTH(b); nab = na + nb - 1; - PROTECT(ab = NEW_NUMERIC(nab)); - for(i = 0; i < nab; i++) REAL(ab)[i] = 0.0; - for(i = 0; i < na; i++) - for(j = 0; j < nb; j++) REAL(ab)[i + j] += REAL(a)[i] * REAL(b)[j]; - UNPROTECT(3); - return(ab); - -} - - -#include "loopmacro.h" -LOOPMACRO_C(convolve7) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve8_cpp.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve8_cpp.cpp deleted file mode 100644 index ee7c95e..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve8_cpp.cpp +++ /dev/null @@ -1,43 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- - -// this version is between the Rcpp_New_ptr and the Rcpp_New_std version -// test elapsed relative user.self sys.self -// 5 Rcpp_New_ptr(REPS, a, b) 0.214 1.000000 0.213 0.001 -// 7 Rcpp_New_std_2(REPS, a, b) 0.223 1.042056 0.216 0.006 -// 4 Rcpp_New_std(REPS, a, b) 0.524 2.448598 0.523 0.001 -// -// so there is some overhead due to creating Vec objects and indexing them -// but much less than when we index the NumericVector - -#include - -class Vec { -public: - Vec( double* data_ ) : data(data_){} - inline double& operator[]( int i){ return data[i] ; } - -private: - double* data ; -} ; - - -RcppExport SEXP convolve8cpp(SEXP a, SEXP b){ - Rcpp::NumericVector xa(a); - Rcpp::NumericVector xb(b); - int n_xa = xa.size() ; - int n_xb = xb.size() ; - int nab = n_xa + n_xb - 1; - Rcpp::NumericVector xab(nab); - - Vec vab(xab.begin()), va(xa.begin()), vb(xb.begin()) ; - - for (int i = 0; i < n_xa; i++) - for (int j = 0; j < n_xb; j++) - vab[i + j] += va[i] * vb[j]; - - return xab ; -} - -#include "loopmacro.h" -LOOPMACRO_CPP(convolve8cpp) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve9_cpp.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve9_cpp.cpp deleted file mode 100644 index 7b7d1b7..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/convolve9_cpp.cpp +++ /dev/null @@ -1,61 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- - -// this version expands convolve8_cpp by making Vec mimic the structure of -// NumericVector. It peforms well, so this is is not the structure of -// NumericVector that is the problem. So what is it then ? -// -// could it be because NumericVector is in a different library than -// this code, so that operator[] is not inlined ? -// -// clues: -// - http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka3538.html - -#include - -class Cache{ -public: - typedef double& proxy ; - typedef double* iterator ; - - Cache( iterator data_) : data(data_){} - - inline proxy ref(int i){ return data[i] ; } - inline proxy ref(int i) const { return data[i] ; } - -private: - iterator data ; -} ; - -class Vec { -public: - typedef double& proxy ; - - Vec( double* data_ ) : cache(data_){} - inline proxy operator[]( int i){ return cache.ref(i) ; } - inline proxy operator[]( int i) const { return cache.ref(i) ; } - -private: - Cache cache ; -} ; - - -RcppExport SEXP convolve9cpp(SEXP a, SEXP b){ - Rcpp::NumericVector xa(a); - Rcpp::NumericVector xb(b); - int n_xa = xa.size() ; - int n_xb = xb.size() ; - int nab = n_xa + n_xb - 1; - Rcpp::NumericVector xab(nab); - - Vec vab(xab.begin()), va(xa.begin()), vb(xb.begin()) ; - - for (int i = 0; i < n_xa; i++) - for (int j = 0; j < n_xb; j++) - vab[i + j] += va[i] * vb[j]; - - return xab ; -} - -#include "loopmacro.h" -LOOPMACRO_CPP(convolve9cpp) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/exampleRCode.r b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/exampleRCode.r deleted file mode 100755 index 47605ef..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/exampleRCode.r +++ /dev/null @@ -1,107 +0,0 @@ -#!/usr/bin/env r - -suppressMessages(require(Rcpp)) -set.seed(42) -n <- 200 -a <- rnorm(n) -b <- rnorm(n) - -## load shared libraries with wrapper code -dyn.load("convolve2_c.so") -dyn.load("convolve3_cpp.so") -dyn.load("convolve4_cpp.so") -dyn.load("convolve5_cpp.so") -dyn.load("convolve7_c.so") - -dyn.load("convolve8_cpp.so") -dyn.load("convolve9_cpp.so") -dyn.load("convolve10_cpp.so") -dyn.load("convolve11_cpp.so") -dyn.load("convolve12_cpp.so" ) -dyn.load("convolve14_cpp.so" ) - -## now run each one once for comparison of results, -## and define test functions - -R_API_optimised <- function(n,a,b) .Call("convolve2__loop", n, a, b) -Rcpp_New_std <- function(n,a,b) .Call("convolve3cpp__loop", n, a, b) -#Rcpp_New_std_inside <- function(n,a,b) .Call("convolve3cpp__loop", n, a, b, PACKAGE = "Rcpp" ) -Rcpp_New_ptr <- function(n,a,b) .Call("convolve4cpp__loop", n, a, b) -Rcpp_New_sugar <- function(n,a,b) .Call("convolve5cpp__loop", n, a, b) -Rcpp_New_sugar_noNA <- function(n,a,b) .Call("convolve11cpp__loop", n, a, b) -R_API_naive <- function(n,a,b) .Call("convolve7__loop", n, a, b) -Rcpp_New_std_2 <- function(n,a,b) .Call("convolve8cpp__loop", n, a, b) -#Rcpp_New_std_3 <- function(n,a,b) .Call("convolve9cpp__loop", n, a, b) -#Rcpp_New_std_4 <- function(n,a,b) .Call("convolve10cpp__loop", n, a, b) -Rcpp_New_std_it <- function(n,a,b) .Call("convolve12cpp__loop", n, a, b ) -Rcpp_New_std_Fast <- function(n,a,b) .Call("convolve14cpp__loop", n, a, b ) - - -v1 <- R_API_optimised(1L, a, b ) -v3 <- Rcpp_New_std(1L, a, b) -v4 <- Rcpp_New_ptr(1L, a, b) -v5 <- Rcpp_New_sugar(1L, a, b ) -v7 <- R_API_naive(1L, a, b) -v11 <- Rcpp_New_sugar_noNA(1L, a, b) - -stopifnot(all.equal(v1, v3)) -stopifnot(all.equal(v1, v4)) -stopifnot(all.equal(v1, v5)) -stopifnot(all.equal(v1, v7)) -stopifnot(all.equal(v1, v11)) - -## load benchmarkin helper function -suppressMessages(library(rbenchmark)) -REPS <- 5000L -bm <- benchmark(R_API_optimised(REPS,a,b), - R_API_naive(REPS,a,b), - Rcpp_New_std(REPS,a,b), -# Rcpp_New_std_inside(REPS,a,b), - Rcpp_New_ptr(REPS,a,b), - Rcpp_New_sugar(REPS,a,b), - Rcpp_New_sugar_noNA(REPS,a,b), - Rcpp_New_std_2(REPS,a,b), -# Rcpp_New_std_3(REPS,a,b), -# Rcpp_New_std_4(REPS,a,b), - Rcpp_New_std_it(REPS,a,b), - Rcpp_New_std_Fast(REPS,a,b), - columns=c("test", "elapsed", "relative", "user.self", "sys.self"), - order="relative", - replications=1) -print(bm) - -cat("All results are equal\n") # as we didn't get stopped -q("no") - - -sizes <- 1:10*100 -REPS <- 5000L -timings <- lapply( sizes, function(size){ - cat( "size = ", size, "..." ) - a <- rnorm(size); b <- rnorm(size) - bm <- benchmark(R_API_optimised(REPS,a,b), - R_API_naive(REPS,a,b), - Rcpp_New_std(REPS,a,b), - Rcpp_New_ptr(REPS,a,b), - Rcpp_New_sugar(REPS,a,b), - Rcpp_New_sugar_noNA(REPS,a,b), - columns=c("test", "elapsed", "relative", "user.self", "sys.self"), - order="relative", - replications=1) - - cat( " done\n" ) - bm -} ) -for( i in seq_along(sizes)){ - timings[[i]]$size <- sizes[i] -} -timings <- do.call( rbind, timings ) - -require( lattice ) -png( "elapsed.png", width = 800, height = 600 ) -xyplot( elapsed ~ size, groups = test, data = timings, auto.key = TRUE, type = "l", lwd = 2 ) -dev.off() -png( "relative.png", width = 800, height = 600 ) -xyplot( relative ~ size, groups = test, data = timings, auto.key = TRUE, type = "l", lwd = 2 ) -dev.off() - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/loopmacro.h b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/loopmacro.h deleted file mode 100644 index c8c3631..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/loopmacro.h +++ /dev/null @@ -1,13 +0,0 @@ - -#define LOOPMACRO_C(name) \ -SEXP name##__loop(SEXP n_, SEXP a, SEXP b){ \ - int n = INTEGER(n_)[0] ; \ - SEXP res = R_NilValue ; \ - for( int i=0; i -// using namespace Rcpp ; - -SEXP overhead_cpp(SEXP a, SEXP b) { - return R_NilValue ; -} - -extern "C" void R_init_overhead_1(DllInfo *info){ - - R_CallMethodDef callMethods[] = { - {"overhead_cpp", (DL_FUNC) &overhead_cpp, 2}, - {NULL, NULL, 0} - }; - - R_registerRoutines(info, NULL, callMethods, NULL, NULL); -} - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/overhead_2.c b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/overhead_2.c deleted file mode 100644 index e59bab1..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/ConvolveBenchmarks/overhead_2.c +++ /dev/null @@ -1,21 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- - -// This is a rewrite of the 'Writing R Extensions' section 5.10.1 example -#include -#include -#include - -SEXP overhead_c(SEXP a, SEXP b) { - return R_NilValue ; -} - -void R_init_overhead_2(DllInfo *info){ - - R_CallMethodDef callMethods[] = { - {"overhead_c", (DL_FUNC) &overhead_c, 2}, - {NULL, NULL, 0} - }; - - R_registerRoutines(info, NULL, callMethods, NULL, NULL); -} - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/benchmark.r b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/benchmark.r deleted file mode 100755 index f994b35..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/benchmark.r +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env r -# -# Comparison benchmark -# -# This shows how Armadillo improves on the previous version using GNU GSL, -# and how both are doing better than lm.fit() -# -# Copyright (C) 2010 Dirk Eddelbuettel and Romain Francois -# -# This file is part of Rcpp. -# -# Rcpp is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 2 of the License, or -# (at your option) any later version. -# -# Rcpp is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Rcpp. If not, see . - -suppressMessages(library(RcppGSL)) -suppressMessages(library(RcppArmadillo)) - -source("lmArmadillo.R") -source("lmGSL.R") - -set.seed(42) -n <- 5000 -k <- 9 -X <- cbind( rep(1,n), matrix(rnorm(n*k), ncol=k) ) -truecoef <- 1:(k+1) -y <- as.numeric(X %*% truecoef + rnorm(n)) - -N <- 100 - -lmgsl <- lmGSL() -lmarma <- lmArmadillo() - -tlm <- mean(replicate(N, system.time( lmfit <- lm(y ~ X - 1) )["elapsed"]), trim=0.05) -tlmfit <- mean(replicate(N, system.time(lmfitfit <- lm.fit(X, y))["elapsed"]), trim=0.05) -tlmgsl <- mean(replicate(N, system.time(lmgsl(y, X))["elapsed"]), trim=0.05) -tlmarma <- mean(replicate(N, system.time(lmarma(y, X))["elapsed"]), trim=0.05) - -res <- c(tlm, tlmfit, tlmgsl, tlmarma) -data <- data.frame(results=res, ratios=tlm/res) -rownames(data) <- c("lm", "lm.fit", "lmGSL", "lmArma") -cat("For n=", n, " and k=", k, "\n", sep="") -print(t(data)) -print(t(1/data[,1,drop=FALSE])) # regressions per second - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/benchmarkLongley.r b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/benchmarkLongley.r deleted file mode 100755 index 9d50447..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/benchmarkLongley.r +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env r -# -# Comparison benchmark -- using old and small Longley data set -# -# This shows how Armadillo improves on the previous version using GNU GSL, -# and how both are doing better than lm.fit() -# -# Copyright (C) 2010 Dirk Eddelbuettel and Romain Francois -# -# This file is part of Rcpp. -# -# Rcpp is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 2 of the License, or -# (at your option) any later version. -# -# Rcpp is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Rcpp. If not, see . - -suppressMessages(library(utils)) -suppressMessages(library(Rcpp)) -suppressMessages(library(inline)) -suppressMessages(library(datasets)) - -source("lmArmadillo.R") -source("lmGSL.R") - -data(longley) - -longleydm <- data.matrix(data.frame(intcp=1, longley)) -X <- longleydm[,-8] -y <- as.numeric(longleydm[,8]) - -N <- 1000 - -lmgsl <- lmGSL() -lmarma <- lmArmadillo() - -tlm <- mean(replicate(N, system.time( lmfit <- lm(y ~ X - 1) )["elapsed"]), trim=0.05) -tlmfit <- mean(replicate(N, system.time(lmfitfit <- lm.fit(X, y))["elapsed"]), trim=0.05) -tlmgsl <- mean(replicate(N, system.time(lmgsl(y, X))["elapsed"]), trim=0.05) -tlmarma <- mean(replicate(N, system.time(lmarma(y, X))["elapsed"]), trim=0.05) - -res <- c(tlm, tlmfit, tlmgsl, tlmarma) -data <- data.frame(results=res, ratios=tlm/res) -rownames(data) <- c("lm", "lm.fit", "lmGSL", "lmArma") -cat("For Longley\n") -print(t(data)) -print(t(1/data[,1,drop=FALSE])) # regressions per second - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/fastLMviaArmadillo.r b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/fastLMviaArmadillo.r deleted file mode 100755 index 628ebe4..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/fastLMviaArmadillo.r +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env r -# -# A faster lm() replacement based on Armadillo -# -# This improves on the previous version using GNU GSL -# -# Copyright (C) 2010 Dirk Eddelbuettel and Romain Francois -# -# This file is part of Rcpp. -# -# Rcpp is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 2 of the License, or -# (at your option) any later version. -# -# Rcpp is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Rcpp. If not, see . - -source("lmArmadillo.R") - -checkLmArmadillo <- function(y, X) { - fun <- lmArmadillo() - res <- fun(y, X) - fit <- lm(y ~ X - 1) - rc <- all.equal( as.numeric(res[[1]]), as.numeric(coef(fit))) & - all.equal( as.numeric(res[[2]]), as.numeric(coef(summary(fit))[,2])) - invisible(rc) -} - -timeLmArmadillo <- function(y, X, N) { - fun <- lmArmadillo(); - meantime <- mean(replicate(N, system.time(fun(y, X))["elapsed"]), trim=0.05) -} - -set.seed(42) -n <- 5000 -k <- 9 -X <- cbind( rep(1,n), matrix(rnorm(n*k), ncol=k) ) -truecoef <- 1:(k+1) -y <- as.numeric(X %*% truecoef + rnorm(n)) - -N <- 100 - -stopifnot(checkLmArmadillo(y, X)) -mt <- timeLmArmadillo(y, X, N) -cat("Armadillo: Running", N, "simulations yields (trimmed) mean time", mt, "\n") diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/fastLMviaGSL.r b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/fastLMviaGSL.r deleted file mode 100755 index 24262f9..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/fastLMviaGSL.r +++ /dev/null @@ -1,52 +0,0 @@ -#!/usr/bin/env r -# -# A faster lm() replacement based on GNU GSL -# -# This first appeared in the 'Intro to HPC tutorials' -# but has been wrapped in inline::cfunction() here -# -# Copyright (C) 2010 Dirk Eddelbuettel and Romain Francois -# -# This file is part of Rcpp. -# -# Rcpp is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 2 of the License, or -# (at your option) any later version. -# -# Rcpp is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Rcpp. If not, see . - -source("lmGSL.R") - -checkLmGSL <- function(y, X) { - fun <- lmGSL() - res <- fun(y, X) - fit <- lm(y ~ X - 1) - rc <- all.equal( res[[1]], as.numeric(coef(fit))) & - all.equal( res[[2]], as.numeric(coef(summary(fit))[,2])) - invisible(rc) -} - -timeLmGSL <- function(y, X, N) { - fun <- lmGSL(); - meantime <- mean(replicate(N, system.time(fun(y, X))["elapsed"]), trim=0.05) -} - -set.seed(42) -n <- 5000 -k <- 9 -X <- cbind( rep(1,n), matrix(rnorm(n*k), ncol=k) ) -truecoef <- 1:(k+1) -y <- as.numeric(X %*% truecoef + rnorm(n)) - -N <- 100 - -stopifnot(checkLmGSL(y, X)) -mt <- timeLmGSL(y, X, N) -cat("GSL: Running", N, "simulations yields (trimmed) mean time", mt, "\n") diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/lmArmadillo.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/lmArmadillo.R deleted file mode 100644 index 35db589..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/FastLM/lmArmadillo.R +++ /dev/null @@ -1,89 +0,0 @@ -# -# lm() via Armadillo -- improving on the previous GSL solution -# -# Copyright (C) 2010 Dirk Eddelbuettel and Romain Francois -# -# This file is part of Rcpp. -# -# Rcpp is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 2 of the License, or -# (at your option) any later version. -# -# Rcpp is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Rcpp. If not, see . - -suppressMessages(require(Rcpp)) - -## NOTE: This is the old way to compile Rcpp code inline. -## The code here has left as a historical artifact and tribute to the old way. -## Please use the code under the "new" inline compilation section. - -suppressMessages(require(inline)) - -lmArmadillo_old <- function() { - src <- ' - - Rcpp::NumericVector yr(Ysexp); - Rcpp::NumericVector Xr(Xsexp); - std::vector dims = Xr.attr("dim") ; - int n = dims[0], k = dims[1]; - - arma::mat X(Xr.begin(), n, k, false); // use advanced armadillo constructors - arma::colvec y(yr.begin(), yr.size()); - - arma::colvec coef = solve(X, y); // fit model y ~ X - - arma::colvec resid = y - X*coef; // to compute std. error of the coefficients - double sig2 = arma::as_scalar(trans(resid)*resid)/(n-k); // requires Armadillo 0.8.2 or later - arma::mat covmat = sig2 * arma::inv(arma::trans(X)*X); - - Rcpp::NumericVector coefr(k), stderrestr(k); - for (int i=0; i. - -suppressMessages(require(Rcpp)) - -## NOTE: This is the old way to compile Rcpp code inline. -## The code here has left as a historical artifact and tribute to the old way. -## Please use the code under the "new" inline compilation section. - -suppressMessages(require(inline)) - -lmGSL_old <- function() { - - src <- ' - - Rcpp::NumericVector Yr(Ysexp); - Rcpp::NumericMatrix Xr(Xsexp); - - int i,j,n = Xr.nrow(), k = Xr.ncol(); - double chisq; - - gsl_matrix *X = gsl_matrix_alloc (n, k); - gsl_vector *y = gsl_vector_alloc (n); - gsl_vector *c = gsl_vector_alloc (k); - gsl_matrix *cov = gsl_matrix_alloc (k, k); - for (i = 0; i < n; i++) { - for (j = 0; j < k; j++) - gsl_matrix_set (X, i, j, Xr(i,j)); - gsl_vector_set (y, i, Yr(i)); - } - - gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc (n, k); - gsl_multifit_linear (X, y, c, cov, &chisq, work); - gsl_multifit_linear_free (work); - - Rcpp::NumericVector coefr(k), stderrestr(k); - for (i = 0; i < k; i++) { - coefr(i) = gsl_vector_get(c,i); - stderrestr(i) = sqrt(gsl_matrix_get(cov,i,i)); - } - gsl_matrix_free (X); - gsl_vector_free (y); - gsl_vector_free (c); - gsl_matrix_free (cov); - - - return Rcpp::List::create( Rcpp::Named( "coef", coefr), - Rcpp::Named( "stderr", stderrestr)); - ' - - ## turn into a function that R can call - ## compileargs redundant on Debian/Ubuntu as gsl headers are found anyway - fun_old <- cxxfunction(signature(Ysexp="numeric", Xsexp="numeric"), - src, - includes="#include ", - plugin="RcppGSL") -} - -## NOTE: Within this section, the new way to compile Rcpp code inline has been -## written. Please use the code next as a template for your own project. - -lmGSL <- function() { - -sourceCpp(code=' -#include -#include -// [[Rcpp::depends(RcppGSL)]] - -// [[Rcpp::export]] -Rcpp::List fun(Rcpp::NumericVector Yr, Rcpp::NumericMatrix Xr){ - - int i, j, n = Xr.nrow(), k = Xr.ncol(); - double chisq; - - RcppGSL::Matrix X(n, k); // allocate a gsl_matrix of dim n, k - RcppGSL::Vector y(n); // allocate a gsl_vector of length n - RcppGSL::Vector c(k); // allocate a gsl_vector of length k - RcppGSL::Matrix cov(k, k); // allocate a gsl_matrix of dim k, k - - for (i = 0; i < n; i++) { - for (j = 0; j < k; j++) - X(i, j) = Xr(i, j); - y[i] = Yr(i); // Note vector requires [] not () - } - - gsl_multifit_linear_workspace *work = gsl_multifit_linear_alloc (n, k); - gsl_multifit_linear (X, y, c, cov, &chisq, work); - gsl_multifit_linear_free (work); - - Rcpp::NumericVector coefr(k), stderrestr(k); - for (i = 0; i < k; i++) { - coefr(i) = c[i]; - stderrestr(i) = sqrt(cov(i,i)); - } - - - return Rcpp::List::create( Rcpp::Named("coef") = coefr, - Rcpp::Named("stderr") = stderrestr); -}') -fun -} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Misc/fibonacci.r b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Misc/fibonacci.r deleted file mode 100755 index 6ae402f..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Misc/fibonacci.r +++ /dev/null @@ -1,46 +0,0 @@ -#!/usr/bin/env r - -## this short example was provided in response to this StackOverflow questions: -## http://stackoverflow.com/questions/6807068/why-is-my-recursive-function-so-slow-in-r -## and illustrates that recursive function calls are a) really expensive in R and b) not -## all expensive in C++ (my machine sees a 700-fold speed increase) and c) the byte -## compiler in R does not help here. - -suppressMessages(library(Rcpp)) - -## byte compiler -require(compiler) - -## A C++ version compile with cppFunction -fibRcpp <- cppFunction( ' -int fibonacci(const int x) { - if (x == 0) return(0); - if (x == 1) return(1); - return (fibonacci(x - 1)) + fibonacci(x - 2); -} -' ) - - -## for comparison, the original (but repaired with 0/1 offsets) -fibR <- function(seq) { - if (seq == 0) return(0); - if (seq == 1) return(1); - return (fibR(seq - 1) + fibR(seq - 2)); -} - -## also use byte-compiled R function -fibRC <- cmpfun(fibR) - -## load rbenchmark to compare -library(rbenchmark) - -N <- 35 ## same parameter as original post -res <- benchmark(fibR(N), - fibRC(N), - fibRcpp(N), - columns=c("test", "replications", "elapsed", - "relative", "user.self", "sys.self"), - order="relative", - replications=1) -print(res) ## show result - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Misc/ifelseLooped.r b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Misc/ifelseLooped.r deleted file mode 100644 index c63bad8..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/Misc/ifelseLooped.r +++ /dev/null @@ -1,101 +0,0 @@ -#!/usr/bin/env r -## -## This example goes back to the following StackOverflow questions: -## http://stackoverflow.com/questions/7153586/can-i-vectorize-a-calculation-which-depends-on-previous-elements -## and provides a nice example of how to accelerate path-dependent -## loops which are harder to vectorise. It lead to the following blog -## post: -## http://dirk.eddelbuettel.com/blog/2011/08/23#rcpp_for_path_dependent_loops -## -## Thanks to Josh Ulrich for provided a first nice (R-based) answer on -## StackOverflow and for also catching a small oversight in my posted answer. -## -## Dirk Eddelbuettel, 23 Aug 2011 -## -## Copyrighted but of course GPL'ed - - -library(inline) -library(rbenchmark) -library(compiler) - -fun1 <- function(z) { - for(i in 2:NROW(z)) { - z[i] <- ifelse(z[i-1]==1, 1, 0) - } - z -} -fun1c <- cmpfun(fun1) - - -fun2 <- function(z) { - for(i in 2:NROW(z)) { - z[i] <- if(z[i-1]==1) 1 else 0 - } - z -} -fun2c <- cmpfun(fun2) - - -funRcpp <- cxxfunction(signature(zs="numeric"), plugin="Rcpp", body=" - Rcpp::NumericVector z = Rcpp::NumericVector(zs); - int n = z.size(); - for (int i=1; i - -using namespace Rcpp; - -// [[Rcpp::export]] -double piSugar(const int N) { - RNGScope scope; // ensure RNG gets set/reset - NumericVector x = runif(N); - NumericVector y = runif(N); - NumericVector d = sqrt(x*x + y*y); - return 4.0 * sum(d < 1.0) / N; -} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/OpenMP/GNUmakefile b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/OpenMP/GNUmakefile deleted file mode 100644 index 1e2ac14..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/OpenMP/GNUmakefile +++ /dev/null @@ -1,30 +0,0 @@ - -## comment this out if you need a different version of R, -## and set set R_HOME accordingly as an environment variable -R_HOME := $(shell R RHOME) - -## include headers and libraries for R -RCPPFLAGS := $(shell $(R_HOME)/bin/R CMD config --cppflags) -RLDFLAGS := $(shell $(R_HOME)/bin/R CMD config --ldflags) - -## include headers and libraries for Rcpp interface classes -RCPPINCL := $(shell echo 'Rcpp:::CxxFlags()' | $(R_HOME)/bin/R --vanilla --slave) -RCPPLIBS := $(shell echo 'Rcpp:::LdFlags()' | $(R_HOME)/bin/R --vanilla --slave) - -## OpenMP -OPENMPFLAGS := -fopenmp - -c_sources := $(wildcard *.c) -c_sharedlibs := $(patsubst %.c,%.o,$(c_sources)) - -cpp_sources := $(wildcard *.cpp) -cpp_sharedlibs := $(patsubst %.cpp,%.o,$(cpp_sources)) - -all : $(c_sharedlibs) $(cpp_sharedlibs) - -%.o : %.c - R CMD SHLIB $< - -%.o : %.cpp - PKG_CPPFLAGS="$(RCPPFLAGS) $(RCPPINCL) $(OPENMPFLAGS)" PKG_LIBS="$(RLDFLAGS) $(RCPPLIBS) $(OPENMPFLAGS)" R CMD SHLIB $< - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/OpenMP/OpenMPandInline.r b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/OpenMP/OpenMPandInline.r deleted file mode 100644 index 31f6e83..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/OpenMP/OpenMPandInline.r +++ /dev/null @@ -1,88 +0,0 @@ -#!/usr/bin/env r - -library(inline) -library(rbenchmark) - -serialCode <- ' - // assign to C++ vector - std::vector x = Rcpp::as >(xs); - size_t n = x.size(); - for (size_t i=0; i x = Rcpp::as >(xs); - std::transform(x.begin(), x.end(), x.begin(), ::log); - return Rcpp::wrap(x); -' -funSerialStdAlg <- cxxfunction(signature(xs="numeric"), body=serialStdAlgCode, plugin="Rcpp") - -## same, but with Rcpp vector just to see if there is measurable difference -serialRcppCode <- ' - // assign to C++ vector - Rcpp::NumericVector x = Rcpp::NumericVector(xs); - size_t n = x.size(); - for (size_t i=0; i x = Rcpp::as >(xs); - size_t n = x.size(); -#pragma omp parallel for shared(x, n) - for (size_t i=0; i - -#ifdef _OPENMP -#include -#endif - -#include - -/** - * Base class for interrupt exceptions thrown when user - * interrupts are detected. - */ -class interrupt_exception : public std::exception { -public: - /** - * Constructor. - * @param[in] message A description of event that - * caused this exception. - */ - interrupt_exception(std::string message) - : detailed_message(message) - {}; - - /** - * Virtual destructor. Needed to avoid "looser throw specification" errors. - */ - virtual ~interrupt_exception() throw() {}; - - /** - * Obtain a description of the exception. - * @return Description. - */ - virtual const char* what() const throw() { - return detailed_message.c_str(); - } - - /** - * String with details on the error. - */ - std::string detailed_message; -}; - -/** - * Do the actual check for an interrupt. - * @attention This method should never be called directly. - * @param[in] dummy Dummy argument. - */ -static inline void check_interrupt_impl(void* /*dummy*/) { - R_CheckUserInterrupt(); -} - -/** - * Call this method to check for user interrupts. - * This is based on the results of a discussion on the - * R-devel mailing list, suggested by Simon Urbanek. - * @attention This method must not be called by any other - * thread than the master thread. If called from within - * an OpenMP parallel for loop, make sure to check - * for omp_get_thread_num()==0 before calling this method! - * @return True, if a user interrupt has been detected. - */ -inline bool check_interrupt() { - return (R_ToplevelExec(check_interrupt_impl, NULL) == FALSE); -} - -/** - * Compute pi using the Leibniz formula - * (a very inefficient approach). - * @param[in] n Number of summands - * @param[in] frequency Check for interrupts after - * every @p frequency loop cycles. - */ -RcppExport SEXP PiLeibniz(SEXP n, SEXP frequency) -{ - BEGIN_RCPP - - // cast parameters - int n_cycles = Rcpp::as(n); - int interrupt_check_frequency = Rcpp::as(frequency); - - // user interrupt flag - bool interrupt = false; - - double pi = 0; -#ifdef _OPENMP -#pragma omp parallel for \ - shared(interrupt_check_frequency, n_cycles, interrupt) \ - reduction(+:pi) -#endif - for (int i=0; i(n); - int thn = as(thin); - - int i,j; - NumericMatrix mat(N, 2); - - RNGScope scope; // Initialize Random number generator - - // The rest of the code follows the R version - double x=0, y=0; - - for (i=0; i - #include - - using namespace Rcpp; // just to be explicit -' - -gslgibbscode <- ' - int N = as(ns); - int thin = as(thns); - int i, j; - gsl_rng *r = gsl_rng_alloc(gsl_rng_mt19937); - double x=0, y=0; - NumericMatrix mat(N, 2); - for (i=0; i. - -## NB This file is mostly historic and predates the unit tests. -## Yet it still provides useful examples -- but the unitTests/ -## for vastly larger coverage - -suppressMessages(library(Rcpp)) -suppressMessages(library(inline)) - -cat("===Doubles\n") -foo <- ' - double d = Rcpp::as(x); - std::cout << "Returning twice the value of " << d << " : "; - return(Rcpp::wrap( 2*d ) ); - ' -funx <- cfunction(signature(x="numeric"), foo, Rcpp=TRUE, verbose=FALSE) -cat(funx(x=2.123), "\n") -cat(funx(x=2), "\n") -##funx(x='2') ## throws as expected -##funx(x=2:3) ## throws as expected - - -cat("\n===Int\n") -foo <- ' - int i = Rcpp::as(x); - std::cout << "Returning twice the value of " << i << " : "; - return(Rcpp::wrap( 2*i ) ); - ' -funx <- cfunction(signature(x="numeric"), foo, Rcpp=TRUE, verbose=FALSE) -cat(funx(x=2), "\n") -cat(funx(x=2.2), "\n") -funx <- cfunction(signature(x="raw"), foo, Rcpp=TRUE, verbose=FALSE) -cat(funx(x=as.raw(2)), "\n") - -cat("\n===String\n") -foo <- ' - std::string s = Rcpp::as(x); - std::cout << "Returning twice the value of " << s << " : "; - return(Rcpp::wrap( s+s ) ); - ' -funx <- cfunction(signature(x="character"), foo, Rcpp=TRUE, verbose=FALSE) -cat(funx(x="abc"), "\n") - -cat("\n===Raw (bytes)\n") -foo <- ' - Rbyte i = Rcpp::as(x) ; - std::cout << "Returning twice the value of " << (int)i << " : "; - return(Rcpp::wrap( (Rbyte)(2*i) ) ); - ' -funx <- cfunction(signature(x="numeric"), foo, Rcpp=TRUE, verbose=FALSE) -cat( funx(x=2), "\n") -funx <- cfunction(signature(x="integer"), foo, Rcpp=TRUE, verbose=FALSE) -cat( funx(x=2L), "\n") -funx <- cfunction(signature(x="raw"), foo, Rcpp=TRUE, verbose=FALSE) -cat( funx(x=as.raw(2)), "\n") - -cat("\n=== logical \n") -foo <- ' -bool b = Rcpp::as(x); -std::cout << "flip " << ( b ? "TRUE" : "FALSE" ) << " : "; -return(Rcpp::wrap( !b )); -' -funx <- cfunction(signature(x="logical"), foo, Rcpp=TRUE, verbose=FALSE) -cat( res <- funx(x=TRUE) , "\n") ; stopifnot( !res ) -cat( res <- funx(x=FALSE), "\n" ) ; stopifnot( res) -funx <- cfunction(signature(x="numeric"), foo, Rcpp=TRUE, verbose=FALSE) -cat( res <- funx(x=2) , "\n") ; stopifnot( !res ) -cat( res <- funx(x=0.0), "\n") ; stopifnot( res) -funx <- cfunction(signature(x="integer"), foo, Rcpp=TRUE, verbose=FALSE) -cat( res <- funx(x=2L), "\n") ; stopifnot( !res ) -cat( res <- funx(x=0L), "\n") ; stopifnot( res) -funx <- cfunction(signature(x="raw"), foo, Rcpp=TRUE, verbose=FALSE) -cat( res <- funx(x=as.raw(2)), "\n") ; stopifnot( !res ) -cat( res <- funx(x=as.raw(0)), "\n") ; stopifnot( res) - -### vectors - -cat("\n===Int Vector via wrap\n") -foo <- ' - std::vector iv = Rcpp::as< std::vector >(x) ; - std::cout << "Returning twice the value of vector : "; - for (size_t i=0; i iv = Rcpp::as< std::vector >(x) ; - std::cout << "Returning twice the value of vector : "; - for (size_t i=0; i iv = Rcpp::as< std::vector >(x) ; - std::cout << "Returning twice the value of vector : "; - for (size_t i=0; i iv = Rcpp::as< std::vector >(x) ; - std::cout << "Returning twice the value of vector : "; - for (size_t i=0; i\n") -foo <- ' -std::vector bv = Rcpp::as< std::vector >(x) ; -std::cout << "Flip the value of vector : "; -for (size_t i=0; i iv = Rcpp::as< std::vector >(x); - std::cout << "Returning twice the value of vector : "; - for (size_t i=0; i\n") -foo <- ' -std::set iv ; -iv.insert( 0 ) ; -iv.insert( 1 ) ; -iv.insert( 0 ) ; -return Rcpp::wrap( iv );' -funx <- cfunction(signature(), foo, Rcpp=TRUE, verbose=FALSE, includes = "#include " ) -print(res <- funx()) -stopifnot( identical( res, 0:1 ) ) - -cat("\n=== set\n") -foo <- ' -std::set ds; -ds.insert( 0.0 ); -ds.insert( 1.0 ); -ds.insert( 0.0 ); -return(Rcpp::wrap( ds )); ' -funx <- cfunction(signature(), foo, Rcpp=TRUE, verbose=FALSE, includes = "#include ") -print( res <- funx() ) -stopifnot( identical( res, as.numeric(0:1))) - -cat("\n=== set\n") -foo <- ' -std::set bs ; -bs.insert( (Rbyte)0 ) ; -bs.insert( (Rbyte)1 ) ; -bs.insert( (Rbyte)0 ) ; -return(Rcpp::wrap( bs )); ' -funx <- cfunction(signature(), foo, Rcpp=TRUE, verbose=FALSE, includes = "#include ") -print( res <- funx() ) -stopifnot( identical( res, as.raw(0:1))) - -cat("\n=== set \n") -foo <- ' -std::set ss ; -ss.insert( "foo" ) ; -ss.insert( "bar" ) ; -ss.insert( "foo" ) ; -return(Rcpp::wrap( ss )); ' -funx <- cfunction(signature(), foo, Rcpp=TRUE, verbose=FALSE, include = "#include " ) -print( res <- funx() ) -stopifnot( identical( res, c("bar","foo")) ) - - -#========= attributes - -funx <- cfunction( - signature(x="data.frame"), ' -std::vector iv = Rcpp::RObject(x).attributeNames(); -return(Rcpp::wrap( iv )); -', Rcpp=TRUE, verbose=FALSE) -res <- funx( iris ) -stopifnot( all( c("names", "row.names", "class" ) %in% res ) ) - -funx <- cfunction(signature(x="data.frame"), ' -bool has_class = Rcpp::RObject(x).hasAttribute( "class" ) ; -return Rcpp::wrap( has_class ) ; -', Rcpp=TRUE, verbose=FALSE) -res <- funx( iris ) -stopifnot( res ) - -funx <- cfunction(signature(x="data.frame"), ' -return Rcpp::RObject(x).attr( "row.names" ) ; -', Rcpp=TRUE, verbose=FALSE) -res <- funx( iris ) -stopifnot( identical(res, 1:150) ) - -#============ NULL -funx <- cfunction(signature(x="ANY"), ' -bool is_null = Rcpp::RObject(x).isNULL() ; -return Rcpp::wrap( is_null ) ; -', Rcpp=TRUE, verbose=FALSE) -res <- funx( iris ) -stopifnot( !res ) -res <- funx( NULL ) -stopifnot( res ) - - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/RcppInline/RcppInlineExample.r b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/RcppInline/RcppInlineExample.r deleted file mode 100755 index 52dd500..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/RcppInline/RcppInlineExample.r +++ /dev/null @@ -1,47 +0,0 @@ -#!/usr/bin/env r - -suppressMessages(library(Rcpp)) - -## NOTE: This is the old way to compile Rcpp code inline. -## The code here has left as a historical artifact and tribute to the old way. -## Please use the code under the "new" inline compilation section. - -suppressMessages(library(inline)) - -foo <- ' - IntegerVector vec(10000); // vec parameter viewed as vector of ints. - int i = 0; - for (int a = 0; a < 9; a++) - for (int b = 0; b < 9; b++) - for (int c = 0; c < 9; c++) - for (int d = 0; d < 9; d++) - vec(i++) = a*b - c*d; - - return vec; -' - -funx_old <- cxxfunction(signature(), foo, plugin = "Rcpp" ) - -## NOTE: Within this section, the new way to compile Rcpp code inline has been -## written. Please use the code next as a template for your own project. - -cppFunction('IntegerVector funx(){ - IntegerVector vec(10000); // vec parameter viewed as vector of ints. - int i = 0; - for (int a = 0; a < 9; a++) - for (int b = 0; b < 9; b++) - for (int c = 0; c < 9; c++) - for (int d = 0; d < 9; d++) - vec(i++) = a*b - c*d; - - return vec; -}') - -dd.inline.rcpp <- function() { - res <- funx() - tabulate(res) -} - -print(mean(replicate(100,system.time(dd.inline.rcpp())["elapsed"]),trim=0.05)) - - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/RcppInline/RcppInlineWithLibsExamples.r b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/RcppInline/RcppInlineWithLibsExamples.r deleted file mode 100755 index e4a6fae..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/RcppInline/RcppInlineWithLibsExamples.r +++ /dev/null @@ -1,351 +0,0 @@ -#!/usr/bin/env r -# -# Copyright (C) 2009 - 2016 Dirk Eddelbuettel and Romain Francois -# -# This file is part of Rcpp. -# -# Rcpp is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 2 of the License, or -# (at your option) any later version. -# -# Rcpp is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Rcpp. If not, see . - -suppressMessages(library(Rcpp)) -suppressMessages(library(RcppGSL)) - -## NOTE: This is the old way to compile Rcpp code inline. -## The code here has left as a historical artifact and tribute to the old way. -## Please use the code under the "new" inline compilation section. - -suppressMessages(library(inline)) - -firstExample_old <- function() { - ## a really simple C program calling three functions from the GSL - gslrng <- ' - gsl_rng *r; - gsl_rng_env_setup(); - double v; - - r = gsl_rng_alloc (gsl_rng_default); - - printf(" generator type: %s\\n", gsl_rng_name (r)); - printf(" seed = %lu\\n", gsl_rng_default_seed); - v = gsl_rng_get (r); - printf(" first value = %.0f\\n", v); - - gsl_rng_free(r); - return R_NilValue; - ' - - ## turn into a function that R can call - ## compileargs redundant on Debian/Ubuntu as gsl headers are found anyway - funx_old <- cxxfunction(signature(), gslrng, - includes="#include ", - plugin="RcppGSL") - - cat("Calling first example\n") - funx_old() - invisible(NULL) -} - -secondExample_old <- function() { - - ## now use Rcpp to pass down a parameter for the seed - gslrng <- ' - int seed = Rcpp::as(par) ; - - gsl_rng *r; - gsl_rng_env_setup(); - double v; - - r = gsl_rng_alloc (gsl_rng_default); - - gsl_rng_set (r, (unsigned long) seed); - v = gsl_rng_get (r); - - #ifndef BeSilent - printf(" generator type: %s\\n", gsl_rng_name (r)); - printf(" seed = %d\\n", seed); - printf(" first value = %.0f\\n", v); - #endif - - gsl_rng_free(r); - return Rcpp::wrap(v) ; - ' - - ## turn into a function that R can call - ## compileargs redundant on Debian/Ubuntu as gsl headers are found anyway - ## use additional define for compile to suppress output - funx_old <- cxxfunction(signature(par="numeric"), gslrng, - includes="#include ", - plugin="RcppGSL") - cat("\n\nCalling second example without -DBeSilent set\n") - print(funx_old(0)) - - - ## now override settings to add -D flag - settings <- getPlugin("RcppGSL") - settings$env$PKG_CPPFLAGS <- paste(settings$PKG_CPPFLAGS, "-DBeSilent") - - funx_old <- cxxfunction(signature(par="numeric"), gslrng, - includes="#include ", - settings=settings) - cat("\n\nCalling second example with -DBeSilent set\n") - print(funx_old(0)) - - invisible(NULL) -} - -thirdExample_old <- function() { - - ## now use Rcpp to pass down a parameter for the seed, and a vector size - gslrng <- ' - int seed = Rcpp::as(s) ; - int len = Rcpp::as(n); - - gsl_rng *r; - gsl_rng_env_setup(); - std::vector v(len); - - r = gsl_rng_alloc (gsl_rng_default); - - gsl_rng_set (r, (unsigned long) seed); - for (int i=0; i(s); - int len = Rcpp::as(n); - - gsl_rng *r; - gsl_rng_env_setup(); - std::vector v(len); - - r = gsl_rng_alloc (gsl_rng_default); - - gsl_rng_set (r, (unsigned long) seed); - for (int i=0; i", - "using namespace Rcpp;", - "using namespace std;"), - plugin="RcppGSL") - cat("\n\nCalling fourth example with seed, length and namespaces\n") - print(funx_old(0, 5)) - - invisible(NULL) -} - -## NOTE: Within this section, the new way to compile Rcpp code inline has been -## written. Please use the code next as a template for your own project. - -firstExample <- function() { - ## a really simple C program calling three functions from the GSL - - sourceCpp(code=' -#include -#include - -// [[Rcpp::depends(RcppGSL)]] - -// [[Rcpp::export]] -SEXP funx(){ - gsl_rng *r; - gsl_rng_env_setup(); - double v; - - r = gsl_rng_alloc (gsl_rng_default); - - printf(" generator type: %s\\n", gsl_rng_name (r)); - printf(" seed = %lu\\n", gsl_rng_default_seed); - v = gsl_rng_get (r); - printf(" first value = %.0f\\n", v); - - gsl_rng_free(r); - return R_NilValue; -}') - - cat("Calling first example\n") - funx() - invisible(NULL) -} - -secondExample <- function() { - - ## now use Rcpp to pass down a parameter for the seed - - ## turn into a function that R can call - ## compileargs redundant on Debian/Ubuntu as gsl headers are found anyway - ## use additional define for compile to suppress output - - gslrng <- ' - #include - #include - - // [[Rcpp::depends(RcppGSL)]] - - // [[Rcpp::export]] - double funx(int seed){ - - gsl_rng *r; - gsl_rng_env_setup(); - double v; - - r = gsl_rng_alloc (gsl_rng_default); - - gsl_rng_set (r, (unsigned long) seed); - v = gsl_rng_get (r); - - #ifndef BeSilent - printf(" generator type: %s\\n", gsl_rng_name (r)); - printf(" seed = %d\\n", seed); - printf(" first value = %.0f\\n", v); - #endif - - gsl_rng_free(r); - return v; - }' - - sourceCpp(code=gslrng, rebuild = TRUE) - - cat("\n\nCalling second example without -DBeSilent set\n") - print(funx(0)) - - - ## now override settings to add -D flag - o = Sys.getenv("PKG_CPPFLAGS") - Sys.setenv("PKG_CPPFLAGS" = paste(o, "-DBeSilent")) - - sourceCpp(code=gslrng, rebuild = TRUE) - - # Restore environment flags - Sys.setenv("PKG_CPPFLAGS" = o ) - - cat("\n\nCalling second example with -DBeSilent set\n") - print(funx(0)) - - invisible(NULL) -} - -thirdExample <- function() { - - ## now use Rcpp to pass down a parameter for the seed, and a vector size - - ## turn into a function that R can call - ## compileargs redundant on Debian/Ubuntu as gsl headers are found anyway - ## use additional define for compile to suppress output - - sourceCpp(code=' - #include - #include - - // [[Rcpp::depends(RcppGSL)]] - - // [[Rcpp::export]] - std::vector funx(int seed, int len){ - - gsl_rng *r; - gsl_rng_env_setup(); - std::vector v(len); - - r = gsl_rng_alloc (gsl_rng_default); - - gsl_rng_set (r, (unsigned long) seed); - for (int i=0; i. - -require(Rcpp) - - -## NOTE: This is the old way to compile Rcpp code inline. -## The code here has left as a historical artifact and tribute to the old way. -## Please use the code under the "new" inline compilation section. - -require(inline) -funx_old <- cxxfunction( - signature(), - 'throw std::range_error("boom"); return R_NilValue ; ', - plugin = "Rcpp" ) - -## NOTE: Within this section, the new way to compile Rcpp code inline has been -## written. Please use the code next as a template for your own project. - -cppFunction(' -SEXP funx(){ - throw std::range_error("boom"); return R_NilValue ; -}') - -tryCatch( funx(), "C++Error" = function(e){ - cat( sprintf( "C++ exception of class '%s' : %s\n", class(e)[1L], e$message ) ) -} ) -# or using a direct handler -tryCatch( funx(), "std::range_error" = function(e){ - cat( sprintf( "C++ exception of class '%s' : %s\n", class(e)[1L], e$message ) ) -} ) -# just to check things carry on -print( rnorm(10) ) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/RcppInline/external_pointer.r b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/RcppInline/external_pointer.r deleted file mode 100755 index 2874ba7..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/RcppInline/external_pointer.r +++ /dev/null @@ -1,113 +0,0 @@ -#!/usr/bin/env r -# -# Copyright (C) 2009 - 2010 Romain Francois -# -# This file is part of Rcpp. -# -# Rcpp is free software: you can redistribute it and/or modify it -# under the terms of the GNU General Public License as published by -# the Free Software Foundation, either version 2 of the License, or -# (at your option) any later version. -# -# Rcpp is distributed in the hope that it will be useful, but -# WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License -# along with Rcpp. If not, see . - -require(Rcpp) -require(inline) - - -## NOTE: This is the old way to compile Rcpp code inline. -## The code here has left as a historical artifact and tribute to the old way. -## Please use the code under the "new" inline compilation section. - -funx_old <- cxxfunction(signature(), ' - /* creating a pointer to a vector */ - std::vector* v = new std::vector ; - v->push_back( 1 ) ; - v->push_back( 2 ) ; - - /* wrap the pointer as an external pointer */ - /* this automatically protected the external pointer from R garbage - collection until p goes out of scope. */ - Rcpp::XPtr< std::vector > p(v) ; - - /* return it back to R, since p goes out of scope after the return - the external pointer is no more protected by p, but it gets - protected by being on the R side */ - return( p ) ; -', plugin = "Rcpp" ) -xp <- funx_old() -stopifnot( identical( typeof( xp ), "externalptr" ) ) - -# passing the pointer back to C++ -funx_old <- cxxfunction(signature(x = "externalptr" ), ' - /* wrapping x as smart external pointer */ - /* The SEXP based constructor does not protect the SEXP from - garbage collection automatically, it is already protected - because it comes from the R side, however if you want to keep - the Rcpp::XPtr object on the C(++) side - and return something else to R, you need to protect the external - pointer, by using the protect member function */ - Rcpp::XPtr< std::vector > p(x) ; - - /* just return the front of the vector as a SEXP */ - return( Rcpp::wrap( p->front() ) ) ; -', plugin = "Rcpp" ) -front <- funx_old(xp) -stopifnot( identical( front, 1L ) ) - - -## NOTE: Within this section, the new way to compile Rcpp code inline has been -## written. Please use the code next as a template for your own project. - -## Use of the cppFunction() gives the ability to immediately compile embedded -## C++ directly within R without having to worry about header specification or -## Rcpp attributes. - -cppFunction(' -Rcpp::XPtr< std::vector > funx(){ - /* creating a pointer to a vector */ - std::vector* v = new std::vector ; - v->push_back( 1 ) ; - v->push_back( 2 ) ; - - /* wrap the pointer as an external pointer */ - /* this automatically protected the external pointer from R garbage - * collection until p goes out of scope. - */ - Rcpp::XPtr< std::vector > p(v) ; - - /* return it back to R, since p goes out of scope after the return - * the external pointer is no more protected by p, but it gets - * protected by being on the R side - */ - return( p ) ; -}') - -xp <- funx() -stopifnot( identical( typeof( xp ), "externalptr" ) ) - -# passing the pointer back to C++ -cppFunction(' -SEXP funx_pt(Rcpp::XPtr< std::vector > p){ - /* Wrapping x as smart external pointer */ - - /* The SEXP based constructor does not protect the SEXP from - * garbage collection automatically, it is already protected - * because it comes from the R side, however if you want to keep - * the Rcpp::XPtr object on the C(++) side - * and return something else to R, you need to protect the external - * pointer, by using the protect member function - */ - - /* Just return the front of the vector as a SEXP */ - return Rcpp::wrap(p->front()); -}') -front <- funx_pt(xp) -stopifnot( identical( front, 1L ) ) - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/SugarPerformance/Timer.h b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/SugarPerformance/Timer.h deleted file mode 100644 index 656fc8d..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/SugarPerformance/Timer.h +++ /dev/null @@ -1,55 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- -// -// Timer.h: Rcpp R/C++ interface class library -- simple timer class -// -// Copyright (C) 2010 Dirk Eddelbuettel and Romain Francois -// -// This file is part of Rcpp. -// -// Rcpp is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 2 of the License, or -// (at your option) any later version. -// -// Rcpp is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Rcpp. If not, see . - - -// Simple timer class based on on ideas in atimer.h / atimer.cxx found a few years ago at -// http://www.cs.uiowa.edu/~sriram/30/fall03/ -// and attributed to Amir Elaguizy while under GPL -// but converted to using gettimeofday/GetSystemTime instead - -#ifndef TIMER_H -#define TIMER_H - -class Timer { -public: - Timer() : sys_time("Sys.time") { Reset(); } - void Start() { start_t = getFractionalSeconds() ; } - void Stop() { - end_t = getFractionalSeconds(); - elapsed = end_t - start_t; // Calculate elapsed time in seconds - cumul += elapsed; - } - void Reset() { end_t = start_t = elapsed = cumul = 0.0; } - double ElapsedTime() { return elapsed; } - double CumulativeTime() { return cumul; } - - -private: - Function sys_time ; - double start_t, end_t, elapsed, cumul; - - double getFractionalSeconds(void) { - return as( sys_time() ) ; - } -}; - -#endif - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/SugarPerformance/Timertest.cpp b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/SugarPerformance/Timertest.cpp deleted file mode 100644 index 6cf06b2..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/SugarPerformance/Timertest.cpp +++ /dev/null @@ -1,31 +0,0 @@ -// -*- mode: c++; compile-command: "g++ -Wall -O3 -o Timertest Timertest.cpp"; c-indent-level: 4; c-basic-offset: 4; tab-width: 8 -*- - -// from http://www.cs.uiowa.edu/~sriram/30/fall03/ - -#include -#include -#include "Timer.h" - -int main() { - Timer test; - - std::cout << "Sleeping 2 seconds" << std::endl; - test.Start(); - sleep(2); - test.Stop(); - std::cout << "Sleep lasted for " << test.ElapsedTime() << " seconds." << std::endl; - std::cout << "Sleeping 1 second" << std::endl; - test.Start(); - sleep(1); - test.Stop(); - std::cout << "Sleep lasted for " << test.ElapsedTime() << " seconds." << std::endl; - std::cout << "Cumulative time is " << test.CumulativeTime() << " seconds." << std::endl; - std::cout << "Reseting" << std::endl; - test.Reset(); - std::cout << "Sleeping 2 seconds" << std::endl; - test.Start(); - sleep(2); - test.Stop(); - std::cout << "Sleep lasted for " << test.ElapsedTime() << " seconds." << std::endl; - std::cout << "Cumulative time is " << test.CumulativeTime() << " seconds." << std::endl; -} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/SugarPerformance/sugarBenchmarks.R b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/SugarPerformance/sugarBenchmarks.R deleted file mode 100755 index ea0f357..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/examples/SugarPerformance/sugarBenchmarks.R +++ /dev/null @@ -1,226 +0,0 @@ -#!/usr/bin/env r - -suppressMessages(library(inline)) -suppressMessages(library(Rcpp)) - -benchmark <- function(start = settings$start, - hand.written = settings$hand.written, - sugar = settings$sugar, - expr = settings$expr, - runs = settings$runs, - data = settings$data, - end = settings$end, - inc = settings$inc, - - settings = list( - start = "", hand.written = "", - sugar = "", expr = NULL, - runs = 500, - data = NULL , - end = "", - inc = "" - ) - ) { - -expr <- force(expr) -inc <- force( inc ) - -src <- sprintf( ' - unsigned int runs = as(runss); - Environment e(env) ; - - %s - - Timer timer; - - // approach one - timer.Start(); - for (unsigned int i=0; i(N); - NumericVector numvec(xvec) ; - Function f(fun) ; - for( int i=0; i fx(x), fy(y), fz(z) ; - int n = x.size() ; - for( int i=0; i nx(x), ny(y) ; - NumericVector z = nx * ny ; - return z ; - } -' - - -fx <- cxxfunction( - list( - direct = signature( x_ = "numeric", y_ = "numeric" ), - extractor = signature( x_ = "numeric", y_ = "numeric" ), - sugar_nona = signature( x_ = "numeric", y_ = "numeric" ), - - assign_direct = signature( x_ = "numeric", y_ = "numeric" ), - assign_extractor = signature( x_ = "numeric", y_ = "numeric" ), - assign_sugar_nona = signature( x_ = "numeric", y_ = "numeric" ) - - ) , - list( - direct = ' - SEXP res = R_NilValue ; - for( int j=0; j<1000; j++) - res = direct__( x_, y_ ) ; - return res ; - ', - extractor = ' - SEXP res = R_NilValue ; - for( int j=0; j<1000; j++) - res = extractors__( x_, y_ ) ; - return res ; - ', - sugar_nona = ' - SEXP res = R_NilValue ; - for( int j=0; j<1000; j++) - res = sugar_nona__( x_, y_ ) ; - return res ; - ', - - assign_direct = ' - NumericVector x( x_ ), y( y_ ), z( x.size() ) ; - int n = x.size() ; - for( int j=0; j<1000; j++) - for( int i=0; i( n_ ) ; - NumericVector x(x_), y(y_), z(x.size()) ; - for( int i=0; i - -R: Seamless R and C++ Integration - - - -

Seamless R and C++ Integration - -

-
-
-[Up] -[Top] -

Documentation for package ‘Rcpp’ version 0.12.12

- - - -

Help Pages

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Rcpp-packageR / C++ interface
$-methodReflection information for an internal c++ class
$-methodc++ internal objects
$-methodRcpp modules
$<--methodc++ internal objects
.DollarNames-methodcompletion
.DollarNames-methodscompletion
areMacrosDefinedEvaluate a C++ Expression
C++Class-classReflection information for an internal c++ class
C++Constructor-classClass "C++Constructor"
C++Field-classClass "C++Field"
C++Function-classClass "C++Function"
C++Object-classc++ internal objects
C++OverloadedMethods-classClass "C++OverloadedMethods"
compileAttributesCompile Rcpp Attributes for a Package
compilerCheckCheck for Minimal (g++) Compiler Version
cppFunctionDefine an R Function with a C++ Implementation
demanglec++ type information
dependsAttributeRcpp::depends Attribute
evalCppEvaluate a C++ Expression
exportAttributeRcpp::export Attribute
exposeClassCreate an Rcpp Module to Expose a C++ Class in R
formals<--methodSet the formal arguments of a C++ function
formals<--methodsSet the formal arguments of a C++ function
initialize-methodRcpp modules
interfacesAttributeRcpp::interfaces Attribute
LdFlags(Deprecated) Rcpp Linker Flags
loadModuleLoad an Rcpp Module into a Package
loadRcppClassCreate a Class Extending a C++ Class
loadRcppModulesLoads Rcpp modules on package startup
ModuleRetrieves an Rcpp module
Module-classRcpp modules
pluginsAttributeRcpp::plugins Attribute
populatePopulates a namespace or an environment with the content of a module
print.bytesc++ type information
prompt-methodRcpp modules
RcppR / C++ interface
Rcpp-deprecatedDeprecated Functions in the Rcpp Package
Rcpp.package.skeletonCreate a skeleton for a new package depending on Rcpp
Rcpp.plugin.makerFacilitating making package plugins
RcppClass-classCreate a Class Extending a C++ Class
RcppLdFlags(Deprecated) Rcpp Linker Flags
RcppUnitTestsRcpp : unit tests results
registerPluginRegister an inline plugin
setRcppClassCreate a Class Extending a C++ Class
show-methodReflection information for an internal c++ class
show-methodClass "C++Function"
show-methodc++ internal objects
show-methodRcpp modules
sizeofc++ type information
sourceCppSource C++ Code from a File or String
- diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/html/R.css b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/html/R.css deleted file mode 100644 index f10f5ea..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/html/R.css +++ /dev/null @@ -1,97 +0,0 @@ -body { - background: white; - color: black; -} - -a:link { - background: white; - color: blue; -} - -a:visited { - background: white; - color: rgb(50%, 0%, 50%); -} - -h1 { - background: white; - color: rgb(55%, 55%, 55%); - font-family: monospace; - font-size: x-large; - text-align: center; -} - -h2 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-size: large; - text-align: center; -} - -h3 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-size: large; -} - -h4 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-style: italic; - font-size: large; -} - -h5 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; -} - -h6 { - background: white; - color: rgb(40%, 40%, 40%); - font-family: monospace; - font-style: italic; -} - -img.toplogo { - width: 4em; - vertical-align: middle; -} - -img.arrow { - width: 30px; - height: 30px; - border: 0; -} - -span.acronym { - font-size: small; -} - -span.env { - font-family: monospace; -} - -span.file { - font-family: monospace; -} - -span.option{ - font-family: monospace; -} - -span.pkg { - font-weight: bold; -} - -span.samp{ - font-family: monospace; -} - -div.vignettes a:hover { - background: rgb(85%, 85%, 85%); -} diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/include/Rcpp.h b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/include/Rcpp.h deleted file mode 100644 index 64be502..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/include/Rcpp.h +++ /dev/null @@ -1,87 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- -// -// Rcpp.h: R/C++ interface class library -// -// Copyright (C) 2008 - 2009 Dirk Eddelbuettel -// Copyright (C) 2009 - 2015 Dirk Eddelbuettel and Romain Francois -// -// This file is part of Rcpp. -// -// Rcpp is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 2 of the License, or -// (at your option) any later version. -// -// Rcpp is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Rcpp. If not, see . - -#ifndef Rcpp_hpp -#define Rcpp_hpp - -/* it is important that this comes first */ -#include - -#include - -#include -#include -#include -#include -#include - -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -// #define RCPP_NEW_DATE_DATETIME_VECTORS 1 -#include - -#include - -#include -#include - -#include - -#include - -#ifndef RCPP_NO_SUGAR -#include -#include -#endif - -// wrappers for R API 'scalar' functions -#include - -// this stays at the very end, because it needs to -// 'see' all versions of wrap -#include - -#include -#include - -#include -#endif diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/include/Rcpp/Benchmark/Timer.h b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/include/Rcpp/Benchmark/Timer.h deleted file mode 100644 index 240597f..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/include/Rcpp/Benchmark/Timer.h +++ /dev/null @@ -1,147 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- -// -// Timer.h: Rcpp R/C++ interface class library -- Rcpp benchmark utility -// -// Copyright (C) 2012 - 2014 JJ Allaire, Dirk Eddelbuettel and Romain Francois -// -// This file is part of Rcpp. -// -// Rcpp is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 2 of the License, or -// (at your option) any later version. -// -// Rcpp is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Rcpp. If not, see . - -#ifndef RCPP_BENCHMARH_TIMER_H -#define RCPP_BENCHMARH_TIMER_H - -#include -#include -#include - -#define R_NO_REMAP -#include - -#if defined(_WIN32) - #define WIN32_LEAN_AND_MEAN - #include -#elif defined(__APPLE__) - #include -#elif defined(linux) || defined(__linux) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__GLIBC__) || defined(__GNU__) || defined(__CYGWIN__) - #include -#elif defined(sun) || defined(__sun) || defined(_AIX) - #include -#else /* Unsupported OS */ - #error "Rcpp::Timer not supported by your OS." -#endif - -namespace Rcpp{ - - typedef uint64_t nanotime_t; - -#if defined(_WIN32) - - inline nanotime_t get_nanotime(void) { - LARGE_INTEGER time_var, frequency; - QueryPerformanceCounter(&time_var); - QueryPerformanceFrequency(&frequency); - - /* Convert to nanoseconds */ - return 1.0e9 * time_var.QuadPart / frequency.QuadPart; - } - -#elif defined(__APPLE__) - - inline nanotime_t get_nanotime(void) { - nanotime_t time; - mach_timebase_info_data_t info; - - time = mach_absolute_time(); - mach_timebase_info(&info); - - /* Convert to nanoseconds */ - return time * (info.numer / info.denom); - } - -#elif defined(linux) || defined(__linux) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__GLIBC__) || defined(__GNU__) || defined(__CYGWIN__) - - static const nanotime_t nanoseconds_in_second = static_cast(1000000000.0); - - inline nanotime_t get_nanotime(void) { - struct timespec time_var; - - /* Possible other values we could have used are CLOCK_MONOTONIC, - * which is takes longer to retrieve and CLOCK_PROCESS_CPUTIME_ID - * which, if I understand it correctly, would require the R - * process to be bound to one core. - */ - clock_gettime(CLOCK_REALTIME, &time_var); - - nanotime_t sec = time_var.tv_sec; - nanotime_t nsec = time_var.tv_nsec; - - /* Combine both values to one nanoseconds value */ - return (nanoseconds_in_second * sec) + nsec; - } - -#elif defined(sun) || defined(__sun) || defined(_AIX) - - /* short an sweet! */ - inline nanotime_t get_nanotime(void) { - return gethrtime(); - } - -#endif - - class Timer { - public: - Timer() : data(), start_time( get_nanotime() ){} - Timer(nanotime_t start_time_) : data(), start_time(start_time_){} - - void step( const std::string& name){ - data.push_back(std::make_pair(name, now())); - } - - operator SEXP() const { - size_t n = data.size(); - NumericVector out(n); - CharacterVector names(n); - for (size_t i=0; i get_timers(int n){ - return std::vector( n, Timer() ) ; - } - - inline nanotime_t now() const { - return get_nanotime() ; - } - - inline nanotime_t origin() const { - return start_time ; - } - - private: - typedef std::pair Step; - typedef std::vector Steps; - - Steps data; - const nanotime_t start_time; - }; - -} - -#endif - diff --git a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/include/Rcpp/DataFrame.h b/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/include/Rcpp/DataFrame.h deleted file mode 100644 index 0f31a87..0000000 --- a/packrat/lib/x86_64-pc-linux-gnu/3.4.1/Rcpp/include/Rcpp/DataFrame.h +++ /dev/null @@ -1,146 +0,0 @@ -// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*- -// -// DataFrame.h: Rcpp R/C++ interface class library -- data frames -// -// Copyright (C) 2010 - 2015 Dirk Eddelbuettel and Romain Francois -// -// This file is part of Rcpp. -// -// Rcpp is free software: you can redistribute it and/or modify it -// under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 2 of the License, or -// (at your option) any later version. -// -// Rcpp is distributed in the hope that it will be useful, but -// WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. -// -// You should have received a copy of the GNU General Public License -// along with Rcpp. If not, see . - -#ifndef Rcpp__DataFrame_h -#define Rcpp__DataFrame_h - -namespace Rcpp{ - - namespace internal{ - inline SEXP empty_data_frame(){ - Shield df( Rf_allocVector(VECSXP, 0) ); - Rf_setAttrib(df, R_NamesSymbol, Rf_allocVector(STRSXP, 0)); - Rf_setAttrib(df, R_RowNamesSymbol, Rf_allocVector(INTSXP, 0)); - Rf_setAttrib(df, R_ClassSymbol, Rf_mkString("data.frame")); - return df; - } - } - - template