Jane Wilkie
Jane Wilkie

Reputation: 1743

Passing vectors and params from Python to R functions

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

Upvotes: 1

Views: 1123

Answers (1)

lgautier
lgautier

Reputation: 11545

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)

Upvotes: 4

Related Questions