简体   繁体   English

在python中使用R脚本,这是为R编写的

[英]Using an R-script in python, which was written for R

A friend has some R-scripts that I might find useful. 朋友有一些我可能觉得有用的R脚本。 But I use Python, and when he upgrades his scripts I want to be able to use his updates. 但我使用Python,当他升级脚本时,我希望能够使用他的更新。

Is it possible to embed R-scripts as-is in Python? 是否有可能在Python中嵌入R脚本?

An typical R-script he might write is named eg quadro.R and has the form: 他可能编写的典型R脚本命名为例如quadro.R,其格式如下:

quadro <- function(x) {
  return(x*x)}

Can I somehow call quadro.R from python with the argument "3" and get the result "9" back in Python? 我可以以某种方式从python中使用参数“3”调用quadro.R并在Python中返回结果“9”吗? I do have R installed on my Linux system. 我的Linux系统上安装了R.

As I understand rpy/rpy2 , I can use R-commands in python but not use an R-script, or did I misunderstood something? 据我了解rpy / rpy2 ,我可以在python中使用R命令但不使用R脚本,或者我误解了什么? Is there some other way to use an R-script from within Python? 是否有其他方法可以在Python中使用R脚本?

First load the whole R script in python, then get any of its R object (function, variable, etc.) assigned and called in python. 首先在python中加载整个R脚本,然后获取在python中分配和调用的任何R对象(函数,变量等)。

An example python script, 一个示例python脚本,

from rpy2 import robjects

robjects.r('''                         
source('quadro.R')
''')                                   #load the R script

quadro = robjects.globalenv['quadro']  #assign an R function in python
quadro(3)                              #to call in python, which returns a list
quadro(3)[0]                           #to get the first element: 9

Rpy2 covers this kind of use rather well, I think. 我认为Rpy2很好地涵盖了这种用途。 You can encapsulate loose R scripts into packages (and avoid storing objects into R's global environment - something that should be as carefully considered as the use of global variables in Python). 您可以将松散的R脚本封装到包中(并避免将对象存储到R的全局环境中 - 这应该像在Python中使用全局变量一样仔细考虑)。

import rpy2.robjects.packages.SignatureTranslatedAnonymousPackage as STAP

with open('quadro.R') as fh:
    rcode = fh.read()
quadro = STAP(rcode, 'quadro')

# The function is now at
quadro.quadro()
# other functions or objects defined in that R script will also be there, for example
# as quadro.foo()

This is in the rpy2 documentation . 这是在rpy2文档中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM