B Python Basics (using R/RStudio)

B.1 Installing tools, R packages, and Python

For reference, Posit provides instructions for using Python from RStudio (including .py files, and Python and R in the same document) at

https://support.posit.co/hc/en-us/articles/1500007929061-Using-Python-with-the-RStudio-IDE

Follow the key steps below.

B.1.1 Get Rtools

You will need some developer tools. If you are on Windows, download the installer and click the .exe to install the latest version of Rtools from

https://cran.rstudio.com/bin/windows/Rtools/rtools43/rtools.html

B.1.2 Get tinytex

Install the tinytex package (and tinytex itself) at the R Console via

install.packages("tinytex")
tinytex::install_tinytex()

B.1.3 Get Python

Download and install Python from

https://www.python.org/downloads/

  • You should tick “add python to PATH”
  • Depending on the configuration of your machine, you may need to install not as an admin

B.1.4 Configure Python

From the RStudio menus, Tools -> Global Options -> Python -> Select -> (select one) -> OK.

Now restart RStudio.

B.1.5 Get reticulate

Install the reticulate package at the R Console via

install.packages("reticulate")

B.2 Using Python

B.2.1 From a Python prompt

To open a Python prompt from within R:

reticulate::repl_python()

B.2.2 From inside a Quarto document

Quarto documents can run both R and Python code.

From the RStudio menus, File -> New File -> Quarto Document. Name and save the .qmd file.

Then, edit one of the code chunks to run python instead of r. Knit the .qmd to (e.g.) .html and see the output. Your Quarto document has run both R and Python. Here’s some sample Python code:

import pandas as pd

df = pd.read_csv("test.csv")

df.shape

To run code from a .py in a Python chunk:

import mypythoncode

To run a .py file from an R chunk:

reticulate::source_python("mypythoncode.py")