This is an example of using Python and R together within a Jupyter notebook. First, let's generate some data within python.


In [2]:
import numpy
%load_ext rpy2.ipython

x=numpy.random.randn(100)
beta=3
y=beta*x+numpy.random.randn(100)

Now, we pass those two variables into R and perform linear regression, and get back the result.


In [5]:
%%R -i x,y -o beta_est
result=lm(y~x)
beta_est=result$coefficients
summary(result)


Call:
lm(formula = y ~ x)

Residuals:
    Min      1Q  Median      3Q     Max 
-2.4064 -0.7397  0.0205  0.6535  3.1228 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)    
(Intercept)  0.06338    0.10217    0.62    0.536    
x            2.95252    0.10224   28.88   <2e-16 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.02 on 98 degrees of freedom
Multiple R-squared:  0.8948,	Adjusted R-squared:  0.8938 
F-statistic:   834 on 1 and 98 DF,  p-value: < 2.2e-16

Now let's look at the contents of the variable that we got back (which should contain the parameter estimates)


In [7]:
print(beta_est)


[ 0.06338464  2.95252381]

In [ ]: