2
votes

This works in Rstudio, and I get the live preview directly in the document when running the chunk. However, when I knit the .Rmd to .html I only get an echo of the code and no output.

```{r engine='Rcpp'}
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int main() {
  return 4;
}

/*** R
main()
*/
```

If I do the same with python, however, I get the proper output when knitting:

```{r engine='python'}
print("abc")
```
1

1 Answers

5
votes

Unfortunately, the comment markup (/***R */) execution does not get retained due to the way it is executed as you noticed. You could say this is an rmarkdown buglet; however, the /***R */ is meant more for an embedding a call during interactive development.

Also, the use of int main() is a big no-no. To quote Dirk:

You can't just drop R context into a standalone main() as you need R for R context.

As a result, I've opted to change the function name to toad().

To achieve the same result and to be true to literate programming, each section should be embedded in separate code chunks. That is, you must create an Rcpp code chunk---preferably with cache enabled---and an R code chunk that contains the actual function call.

e.g.

---
title: Test Doc
author: JJB
date: 6/9/2017
output: html_document
---


```{Rcpp hpc-code, cache = TRUE}
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int toad() {
  return 4;
}
```

```{r interactive-output}
toad()
```

Sample output