Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embed R code in python

Tags:

python

r

I need to make computations in a python program, and I would prefer to make some of them in R. Is it possible to embed R code in python ?

like image 485
alinsoar Avatar asked Jan 27 '13 19:01

alinsoar


People also ask

Can I use R code in Python?

You can import any Python library and write any Python code you want, and then access the variables and functions declared with R. And that's how you can run Python code in R and R Markdown.

Can you import R into Python?

Getting started. The rpy2 Python package will perform the magic that allows us to use R packages in our Python session. The importr function give us the power to import R packages and pandas2ri —along with the subsequent pandas2ri.

Does R integrate well with Python?

Data Scientist With RStudio products you can combine R and Python seamlessly without extra overhead. You can use the RStudio IDE for R, but also for bilingual tasks. With RStudio Workbench, launch Jupyter Notebooks, JupyterLab, or VS Code for Python.


2 Answers

You should take a look at rpy (link to documentation here).

This allows you to do:

from rpy import *

And then you can use the object called r to do computations just like you would do in R.

Here is an example extracted from the doc:

>>> from rpy import *
>>>
>>> degrees = 4
>>> grid = r.seq(0, 10, length=100)
>>> values = [r.dchisq(x, degrees) for x in grid]
>>> r.par(ann=0)
>>> r.plot(grid, values, type=’lines’)
like image 56
Charles Menguy Avatar answered Oct 02 '22 14:10

Charles Menguy


RPy is your friend for this type of thing.

The scipy, numpy and matplotlib packages all do simular things to R and are very complete, but if you want to mix the languages RPy is the way to go!

from rpy2.robjects import *

def main(): 
    degrees = 4 
    grid = r.seq(0, 10, length=100) 
    values = [r.dchisq(x, degrees) for x in grid] 
    r.par(ann=0) 
    r.plot(grid, values, type='l') 

if __name__ == '__main__': 
     main()
like image 21
Matt Alcock Avatar answered Oct 02 '22 16:10

Matt Alcock