Powerful R Markdown for Python Users | by Rahul Bhadani | Towards Data Science

R Markdown is a powerful tool that lets you generate rich PDF using TeX engine. In R Markdown you can integrate prose and your analysis along with code, its outputs, and graphics. However, the use of R Markdown is not limited to the R language itself but a variety of other languages can be integrated.
When it comes to writing your code along with explanations and descriptions, R Markdown is very similar to Jupyter Notebook, but there are several things that R Markdown can do that Jupyter Notebook lacks. For example, with Jupyter Notebook, it is not straightforward to include a custom LaTeX package. With R Markdown, I found out that it is very easy to include a custom LaTeX page. It also lets you generate a PDF file if you have a LaTeX engine installed in your system, with code, its output, and graphics generated in the same PDF/HTML report.
R Markdown uses knitr, which is a dynamic report generation engine for the R language. It can generate a fully reproducible notebook in multiple formats such as PDF and HTML. Knitr engine incorporates various languages such as R, Python, Bash, and SQL. For this article, I am limiting myself to Python and Bash.
To appreciate the article fully and follow along, please install R Studio and R. I am using Ubuntu OS for my examples. However, all examples should work with Windows or Mac with some extra steps that I won’t go into detail about in this article.
Once you have installed R language and R Studio, click to create a new R Notebook.
You can also choose R Markdown which will let you create project-style files. But creating an R Notebook is the simplest to use. The file can be saved in.Rmd format.
Following is a code snippet for .Rmd that you must have.
---title: "My R Markdown Notebook"author:     - Rahul Bhadani^[The University of Arizona, rahulbhadani@email.arizona.edu]date: "`r format(Sys.time(), '%d %B %Y')`"bibliography: biblio.biboutput:    pdf_document:    citation_package: natbib    keep_tex: yes    number_sections: yes  html_notebook: default  html_document:    df_print: pagedclassoption:- onecolumnheader-includes:- \usepackage[none]{hyphenat}- \usepackage{physics}- \graphicspath{ {figures/} }- \usepackage{color}- \definecolor{ocre}{RGB}{243,102,25}- \usepackage[font={color=ocre,bf},labelfont=bf]{caption}- \usepackage{hyperref}- \hypersetup{colorlinks=true,citecolor=blue}- \def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em    T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}- \newcommand{\spliteq}[1]{\begin{equation}\begin{split}#1\end{split}\end{equation}}keep_tex: yesabstract: This is my abstract---# Section 1# Section 2```{r setup, include=FALSE}knitr::opts_chunk$set(echo = TRUE)``````{r, echo=T,eval=T,warning=FALSE, fig.height = 4, fig.width = 5}library('nloptr')hn <- function(x, n){    hret <- 0    if (n == 0)    {       hret <- x + 2*x    }    else    {       hret <- x - 2*x    }    return (hret)}```
In the above code snippet, anything between --- is metadata that defines how to generate TeX files and corresponding PDFs. Using bibliography: , you can specify what .bib to include for citation in your Markdown. You can specify an additional LaTeX command following - command. keep_tex tells R Markdown not to delete generated TeX files which is helpful for several reasons, including further modifying generated tex files if you decide to do so.
Anything within ``` is a code snippet that is executed when eval=T is set.
To generate PDF, click Knit to PDF from Knit options as shown below:
Once the compilation is done, you will see that a PDF file is opened. Additional options can be explored by clicking the settings icon shown above, next to the Knit button. TeX source files will be generated in the same directory where you save the .Rmd file.
To add python code to the R Markdown file, add the following code snippets:
```{python, engine.path =  "/home/username/anaconda3/envs/virtualenv/bin/python", fig.height = 3, fig.width = 6}import pandas as pdimport seaborn as snsiris = sns.load_dataset('iris')iris.head()iris['sepal_length'].plot()```
With engine.path , I am specifying where to look for a python executable to run the python code snippet. Upon running the above code, I can see the following content in my PDF file:
To execute a bash command, you will need to add the following code snippet:
```{bash, engine.opts='-l'}source ~/.bashrcsource /opt/ros/melodic/setup.bashsource ~/catkin_ws/devel/setup.bashpwdls```
When you finish executing your notebook, you will see the output of pwd and ls in your PDF.
There are some limitations in executing bash commands using the knitr engine. In R Markdown, bash is invoked with the R function system2().It ignores profile files like ~/.bash_profile and ~/.bash_login, in which you may have defined aliases, environment variables, and some additional customization. For the same reason, in the above example, you can see that I have explicitly specified to source .bashrc and any other sourcing that I otherwise include inside the .bashrc file.
Further, you should not include any perpetual running bash commands in bash code snippets when including in R, as knitr will keep waiting for the execution to finish only to get disappointed.
R Markdown provides an elegant way to generate reports in various formats for your data analysis. Using R Markdown you can include code, data, outputs, and generated graphics. Finally, you can share variables between R and Python code snippets as well.
For example, to access any R artifacts inside python snippets use r. followed by any variable or function defined in R. Similarly, to access any python artifacts inside R, using py$ followed by any variable or function defined in Python. The following code snippets explain the idea:
# Use Python artifacts from R```{r,echo=T,eval=T,warning=FALSE, fig.height = 4, fig.width = 5}py$iris```# Use R artifacts from Python```{python, engine.path =  "/home/ivory/anaconda3/envs/dbn/bin/python", fig.height = 3, fig.width = 6}print(r.hn(3,5))```
Note: The author created all the examples provided in this article based on his understanding of the technology. The resemblance with any other online resources available may be purely coincidental.