Python can be run directly from R markdown file. It requires that python be specified instead of R. The use of python here requires that Miniconda or Anaconda be installed. Installation of Miniconda via reticulate package will be shown below.
import pandas as pdimport matplotlib.pyplot as pltimport numpy as np#dataset containing locations of ms clinics in Victoriadataset = pd.read_csv('./Data-Use/msclinic.csv') #Read data from CSV datafiledat=pd.DataFrame(dataset)#print 10 rowsprint(dat.head(10))
The data can now be plotted using matplotlib library from Python.
import pandas as pdimport matplotlib.pyplot as pltimport numpy as npimport math#Matplotlibplt.title("Heart Rate Signal") #The title of our plot#ECG is data frame and hart is the columnplt.plot(r.ECG.hart) #Draw the plot object#Display the plotplt.show() exit
5.0.1 Reticulate
Information on the use of Python in R is available at https://rstudio.github.io/reticulate/. The package reticulate can import Python function to work directly in R. Note that the chunk code heading here is r.
library(reticulate)os <-import("os") #os is operating system packageos$listdir(".")
Here we provide another example on how to use Python in R. Note the change in the way we extract the stats module from scipy Python package.
data("mtcars") #mtcars data in Rlibrary(reticulate)np<-import("numpy")pd<-import("pandas")#equivalent in Python is from scipy import statssc<-import("scipy")sc$stats$linregress(mtcars$mpg,mtcars$cyl)
Miniconda and Anaconda can be installed directly from its website. Here we will illustrate installation of Miniconda from Rstudio. The install_miniconda function from reticulate library download Miniconda from the web.
#library(reticulate)#this function is turned off as it only needs to be done once#install_miniconda(path = miniconda_path(), update = TRUE, force = FALSE)
To find the libraries install in Miniconda
conda_list ()
5.0.3 Python environment
Unless specified, the default environment is r-reticulate. Setting the Python environment is important to avoid package incompatibility. To set the environment
library(reticulate)#create virtual environment SignalProcessing#virtualenv_create("SignalProcessing")#activate virtual environment#source SignalProcessing/bin/activate#check version of python#reticulate::py_config()
Some Python libraries such as pycox can be installed in R using install_py… this way.
library(reticulate)#library(survivalmodels)#install pycox for survivalmodels#install_pycox(pip = TRUE, install_torch = TRUE)#install_keras(pip = TRUE, install_tensorflow = TRUE)#install other Python packages#this is similar to pip install torch#install_torch(method = "auto", conda = "auto", pip = TRUE)