There is a lot of information on using Python code in a Markdown document. But it all seems to be about demonstrating Python snippets, not creating good looking documents.
Can I not combine Python and Markdown in a single document, like you can with R and Markdown?
MWE:
Output some text from Python in **Markdown**:
```python
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
print(clf.predict_proba(iris.data[:1, :]))
```
Compiling this: markdown_py markdown.txt
<p>Output some text from Python in <strong>Markdown</strong>:
<code>python
from sklearn.datasets import load_iris
from sklearn import tree
iris = load_iris()
clf = tree.DecisionTreeClassifier()
clf = clf.fit(iris.data, iris.target)
clf.predict_proba(iris.data[:1, :])</code></p>
It displays the code (cool), but does not actually run it.
Can you not run Python code in Markdown? If not, what alternatives are there?
(Using the python-markdown package from Ubuntu.)
The reticulate package includes a Python engine for R Markdown that enables easy interoperability between Python and R chunks.
You can open it here in RStudio Cloud. or by typing the chunk delimiters ```{r} and ``` . When you render your . Rmd file, R Markdown will run each code chunk and embed the results beneath the code chunk in your final report.
Python has the IPython notebook which is extremely like RMarkdown and it is very useful. The IPython Notebook. It works locally on your website and it is interactive just like how R works. When you are done, you can output it to html, pdf and share your analysis with others.
Well, I just found a solution:
Use chunks as:
<<engine='python', engine.path='python3'>>=
# python code
@
engine.path
by default uses the python
executable, which in most Linux systems still is python2
. You can ommit it if you want Python 2.echo=FALSE
if you want to ommit code printout, and results='asis'
so that it does not try to escape the output.You can use the following chunk at the beggining of the document to set the defaults:
<<r setup, include=FALSE>>=
knitr::opts_chunk$set(echo=FALSE, engine='whathaveyou', ...)
@
Save the file as markdown.Rmd, and use R with knitr to compile it. It will run the Python code using python.
R command: rmarkdown::render('markdown.Rmd','output.html')
Or just use RStudio.
Addendum: A native solution is apparently Pweave: it works with latex and markdown. I have not tried it yet though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With