The knitr
package can execute a variety of language chunks:
For Python, instead of {r}
, we begin the code chunk with {python}
.
= 'hello, python world!'
x print(x.split(' '))
## ['hello,', 'python', 'world!']
Chunk options echo
and results
are all valid when using Python.
If the Python code generates raw HTML or LaTeX, the results='asis'
option ensures that it is passed straight into the document’s output stream.
def aucarre(x):
print(x ** 2)
= 3
a aucarre(a)
9
By default, the interpreter returned by Sys.which("python")
is used to execute the code. We can use a different python interpreter with engine.path"/Users/me/anaconda/bin/python"
option.
import sys
print(sys.version)
Exchanging data between R chunks and Python chunks (and between Python chunks) is done via the file system.
With data frames, we can use the feather
package.
feather
1 transfer a data frame created with Pandas to R for plotting with ggplot2
:
Import the data with Python.
import pandas
import feather
= pandas.read_csv("img/mtcars.csv")
cars
"img/cars.feather") feather.write_dataframe(cars,
Read the feather file from R and plot the data frame using ggplot2
.
library(feather)
<- read_feather("img/cars.feather")
mtcars2
head(mtcars2, 3)
mpg <dbl> | cyl <dbl> | disp <dbl> | hp <dbl> | drat <dbl> | wt <dbl> | qsec <dbl> | vs <dbl> | am <dbl> | gear <dbl> | |
---|---|---|---|---|---|---|---|---|---|---|
21.0 | 6 | 160 | 110 | 3.90 | 2.620 | 16.46 | 0 | 1 | 4 | |
21.0 | 6 | 160 | 110 | 3.90 | 2.875 | 17.02 | 0 | 1 | 4 | |
22.8 | 4 | 108 | 93 | 3.85 | 2.320 | 18.61 | 1 | 1 | 4 |
library(ggplot2)
ggplot(mtcars2, aes(mpg, disp)) +
geom_point() +
geom_jitter()