A little something to play with…
Start with a single Rcpp document.
````{r , comment=NA, echo=FALSE, results='asis'}
cat( readLines("./knitrRcpp.cpp"), sep = "\n" )
````
#include <Rcpp.h>
using namespace Rcpp;
// Below is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp
// function (or via the Source button on the editor toolbar)
// [[Rcpp::export]]
int timesTwo(int x) {
return x * 2;
}
/*** R
## ---- timesTwo ----
timesTwo(1)
## ----
*/
// [[Rcpp::export]]
int timesThree(int x) {
return x * 3;
}
/*** R
## ---- timesThree ----
timesThree(1)
## ----
*/
/*** R
## ---- tests ----
require(testthat)
(expect_that( timesTwo(3), equals( timesThree(2) ) ))
(expect_that( timesTwo(6), equals( timesThree(4) ) ))
## ----
*/
And read it into the knitr environment.
````{r rcpp, include=FALSE, cache=FALSE}
Rcpp::sourceCpp("./knitrRcpp.cpp")
knitr::read_chunk("./knitrRcpp.cpp")
````
Now the named knitr chunks in the embedded R can be used as named chunks.
````{r timesTwo}
````
timesTwo(1)
## [1] 2
````{r timesThree}
````
timesThree(1)
## [1] 3
````{r tests, eval=FALSE}
````
````{r tests, echo=FALSE, collapse=TRUE}
````
require(testthat)
(expect_that( timesTwo(3), equals( timesThree(2) ) ))
(expect_that( timesTwo(6), equals( timesThree(4) ) ))
## As expected: timesTwo(3) equals timesThree(2)
## As expected: timesTwo(6) equals timesThree(4)