Embed R code in python

Question:

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 ?

Asked By: alinsoar

||

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’)
Answered By: 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()
Answered By: Matt Alcock

When I need to do R calculations, I usually write R scripts, and run them from Python using the subprocess module. The reason I chose to do this was because the version of R I had installed (2.16 I think) wasn’t compatible with RPy at the time (which wanted 2.14).

So if you already have your R installation “just the way you want it”, this may be a better option.

Answered By: BenDundee

Using rpy2.objects. (Tried and ran some sample R programs)

from rpy2.robjects import r

print(r('''
# Create a vector.
apple <- c('red','green',"yellow")
print(apple)

# Get the class of the vector.
print(class(apple))

##########################

# Create the data for the chart.
v <- c(7,12,28,3,41)

# Give the chart file a name.
png(file = "line_chart.jpg")

# Plot the bar chart. 
plot(v,type = "o")

# Save the file.
dev.off()

##########################

# Give the chart file a name.
png(file = "scatterplot_matrices.png")

# Plot the matrices between 4 variables giving 12 plots.

# One variable with 3 others and total 4 variables.

pairs(~wt+mpg+disp+cyl,data = mtcars,
   main = "Scatterplot Matrix")

# Save the file.
dev.off()

install.packages("plotly")  # Please select a CRAN mirror for use in this session
library(plotly)  # to load "plotly"

'''))
Answered By: Sreedhar_K
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.