使用 rpy2 从 Python 调用自定义函数 [英] Calling Custom functions from Python using rpy2

查看:51
本文介绍了使用 rpy2 从 Python 调用自定义函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法调用文件中定义的函数,比如 myfunc.r

Is there a way to call functions defined in a file say myfunc.r

---------------myfunc.r --------------
myfunc = function(){
  return(c(1,2,3,4,5,6,7,8,9,10))
}

getname = function(){
  return("chart title")
}

---- Python 
   How to call getname() here ?

任何帮助将不胜感激?

推荐答案

rpy2 中的一些功能应该有助于使其比将对象转储到全局工作区更干净.

There are features in rpy2 that should help making this cleaner than dumping objects into the global workspace.

from rpy2.robjects.packages import STAP
# if rpy2 < 2.6.1 do:
# from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage
# STAP = SignatureTranslatedAnonymousPackage
with open('myfunc.r', 'r') as f:
    string = f.read()
myfunc = STAP(string, "myfunc")

现在可以使用 myfunc.myfuncmyfunc.getname 访问 R 文件中的对象.

The objects in the R file can now be accessed with myfunc.myfunc and myfunc.getname.

查看关于将任意 R 代码作为包导入.

这篇关于使用 rpy2 从 Python 调用自定义函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆