Passing vectors and params from Python to R functions

故事扮演 提交于 2019-12-08 03:38:18

问题


I am learning Python and R and am having an issue passing parameters from Python to an R function named "Contours". The below works.....

Python (testr.py)

import rpy2.robjects as robjects
robjects.r('''
       source('Wrapper.R')
''')

r_myfunc = robjects.globalenv['Contours']
r_myfunc()

R (Wrapper.R)

source ('./DrawCompRecVark.R')
imageDirectory="./tmp/"
    Contours <- function()
    {
      k=c(0,1)
      sens=c(0.8, 0.9, 0.95, 0.995)
      spec=0.8
      prev=0.001
      N=1
      uniqueId=1
      #graph
      prepareSaveGraph(imageDirectory, "PPVkSensSpec-", uniqueId)
      DrawSensSpec(k, sens, spec, prev, N)
      dev.off()

      #save the cNPV graph
      prepareSaveGraph(imageDirectory, "cNPVkSensSpec-", uniqueId)
      DrawVarcSpec(k, sens, spec, prev, N)
      dev.off()
    }

So as you can tell, my hard coding of the values in the R code works fine, it's the passing from Python to R that throws me. I tried this....

R function

Contours <- function(k, sens, spec, prev, N, uniqueId)

and trying to pass from Python like this....

r_myfunc( c(0,1), c(0.8, 0.9, 0.95, 0.995), 0.8, 0.001, 1, 986)

and

r_myfunc( "c(0,1)", "c(0.8, 0.9, 0.95, 0.995)", 0.8, 0.001, 1, 986)

Neither of which work. Has anyone encountered this before? Any pointers in the right direction would be greatly appreciated. JW


回答1:


You can import an R source as if it was a package (see http://rpy.sourceforge.net/rpy2/doc-2.5/html/robjects_rpackages.html#importing-arbitrary-r-code-as-a-package)

import os
from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage

with open('Wrapper.R') as fh:
    rcode = os.linesep.join(fh.readlines())
    wrapper = SignatureTranslatedAnonymousPackage(rcode, "wrapper")

Now to call the function Contours present in that namespace, you'll just use wrapper.Contours but you'll have to use Python syntax. In R scalars are vectors of length 1, but in Python scalars and sequences are quite different.

If you want to use R's c():

from rpy2.robjects.packages import importr
base = importr("base")
wrapper.Contours(base.c(0,1),
                 base.c(0.8, 0.9, 0.95, 0.995),
                 0.8, 0.001, 1, 986)

Otherwise:

from rpy2.robjects.vectors import IntVector, FloatVector
wrapper.Contours(IntVector((0,1)),
                 FloatVector((0.8, 0.9, 0.95, 0.995)),
                 0.8, 0.001, 1, 986)


来源:https://stackoverflow.com/questions/28373343/passing-vectors-and-params-from-python-to-r-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!