RPy2 can only be used to call R from Python, and not the other way around. We will import some sample R datasets and plot the data of one of them.
The complete code for this recipe is in the rdatasets.py
file in this book's code bundle:
from rpy2.robjects.packages import importr import numpy as np import matplotlib.pyplot as plt datasets = importr('datasets') mtcars = datasets.__rdata__.fetch('mtcars')['mtcars'] plt.title('R mtcars dataset') plt.xlabel('wt') plt.ylabel('mpg') plt.plot(mtcars) plt.grid(True) plt.show()
The motorcars
dataset is described at https://stat.ethz.ch/R-manual/R-devel/library/datasets/html/mtcars.html. Let's start by loading this sample R dataset:
Load a dataset into an array with the RPy2
importr()
function. This function can importR
packages. In this example, we will import the datasets R package. Create a NumPy array from themtcars
dataset:datasets = importr('datasets...