在Python中嵌入R代码

14
我需要在 Python 程序中进行计算,并且我更倾向于在 R 中进行其中一些计算。是否有可能在 Python 中嵌入 R 代码?
4个回答

8

您应该看一下rpy(文档链接在此)。

这使您可以实现以下内容:

from rpy import *

然后您可以使用名为r的对象进行计算,就像在R中一样。

这是从文档中提取的示例:

>>> 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’)

我认为rpy不适用于最近的R版本或Python 3。 - lgautier

8

RPy 是处理这类事情的好帮手。

Scipy、Numpy 和 Matplotlib 包都可以像 R 一样完成很多事情,而且非常完整。但如果你想要混合使用语言,那么选择 RPy 就是最好的选择!

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()

我完全不了解rpy(Python也只是略知一二),但是:看起来你正在Python中迭代grid。如果可能的话,调用r.dchisq(grid,degrees),即向R进行矢量化调用,是否更有效率?(编辑:我看到另一个答案有相同的例子,源自文档...所以可能有很好的理由?) - Ben Bolker

4
当我需要进行R计算时,我通常会编写R脚本,并使用subprocess模块从Python中运行它们。我之所以选择这样做,是因为我安装的R版本(我想是2.16)当时与RPy不兼容(RPy需要2.14版本)。因此,如果您已经将R安装“按照您的意愿”配置好了,这可能是更好的选择。

0

使用rpy2.objects。(尝试并运行了一些R程序示例)

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"

'''))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接