2.6 Python with RMarkdown

R and Python is relatively straightforward in RStudio:

2.6.1 Setting up Python with RMarkdown

To avoid any unexpected effects when using Python in RStudio, you need to install and use the reticulate package:

```{r}
library(reticulate)
```

To evaluate Python code in RMarkdown, you need to specify the code chunk as:

```{python}
#Example Python code:
print("Hello, world!")
x = 2
print(x)
```

It is important that Python is included in your Windows PATH variables, Otherwise, R will not find it and you will need to specify the engine manually for each block, for example:

```{python engine.path="C:\\Python\\Python37\\python.exe"}
print("Hello, world!")
x = 2
print(x)
```

It is important to note that, unlike R chunks, in RStudio different Python chunks may not allow to share the same variables in some setups (though this may depend on the Python setup used, as well as updates to R and Python libraries).

2.6.2 C++ with RMarkdown using Rcpp

Firstly, download Rtools. During the installation do not modify the installation directory and select to modify the Windows PATH variable:

In the next step add the following to the PATH:

  • C:\Rtools\bin;
  • C:\Rtools\mingw_32\bin;

We can then use C++ with the following code:

```{Rcpp}
#include <Rcpp.h>

#include <iostream>
using namespace std;

// [[Rcpp::export]]
std::string cppHi() {
  return "Hello, World!";
}
```

which we can then call from an R chunk:

```{r}
cppHi()
```

which gives the following output:

## [1] "Hello, World!"