Running R and Matlab Commands in an Ipython Notebook
The ipython notebook environment is a superb environment for empirical research. Sometimes, though, you would like to access the capabilities of other software. This post shows how to incorporate R and Matlab into ipython notebooks.
In [1]:
%matplotlib inline
%load_ext rmagic
%load_ext pymatbridge
In [2]:
import numpy as np
import pandas as pd
import statsmodels.api as sm
data = pd.DataFrame(np.random.rand(100,2),columns=['x','y'])
data.head()
Out[2]:
In [3]:
# plot the data in a x,y scatter
data.plot(kind='scatter', x='x', y='y')
Out[3]:
In [4]:
# run a regression model
results = pd.ols(y=data['y'], x=data[['x']])
results
Out[4]:
Running the same analysis and plot in R and viewing in the Ipython Notebook¶
In [5]:
# push x,y to R
x=data.x
y=data.y
%Rpush x y
In [6]:
%%R
fit <- lm(y ~ x) # Least-squares regression
summary(fit) # Display the coefficients of the fit.
In [7]:
%%R
plot(x,y) # Plot the data points.
To accomplish this, we needed to install the "R magic" python package called rmagic. There is a similar package for matlab called python-matlab-bridge which has a magic called pymatbridge.
Running the same analysis in Matlab and viewing in the Ipython Notebook¶
In [8]:
#pymatbridge requires x,y to be lists for passing:
x = data.x.values.tolist()
y = data.y.values.tolist()
In [9]:
%%matlab -i x,y
x = horzcat(ones(rows(x'),1),x');
y=y';
ols(y,x)
scatter(x(:,2),y)