我需要在 Python 程序中进行计算,并且我更倾向于在 R 中进行其中一些计算。是否有可能在 Python 中嵌入 R 代码?
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 Bolkersubprocess
模块从Python中运行它们。我之所以选择这样做,是因为我安装的R版本(我想是2.16)当时与RPy不兼容(RPy需要2.14版本)。因此,如果您已经将R安装“按照您的意愿”配置好了,这可能是更好的选择。使用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"
'''))
rpy
不适用于最近的R版本或Python 3。 - lgautier