Search code examples
pythonrrservepyrserve

How to call an R function with a dot in its name by pyRserve?


pyRserve module is really handy when interacting with Rserve session from python.

You get access to an R object by prefix its name with expression like "conn.r" or "conn.ref"

import pyRserve
import numpy
conn = pyRserve.connect()
conn.r.List = [1.1, 2.2, 3.3]
conn.r.sapply(conn.ref.List, conn.ref.as.integer)
Out[23]: array([ 1,  2 ,  3])

But this won't work if there's a dot in the function name,

conn.r.sapply(conn.ref.List, conn.ref.as.integer)
    conn.r.sapply(conn.ref.List, conn.ref.as.integer)
                                           ^
SyntaxError: invalid syntax

the only solution I came up with is to wrap the whole R expression in a string and run it using eval function:

conn.eval('result = as.integer(List)')
conn.r.result
Out[46]: array([1, 2, 3], dtype=int32)

Is there any more productive way of doing it?

Note: I realized in another SO thread similar question has been asked an answered for rpy2 module (another python R binding).


Solution

  • finally i found a solution which is inspired by this thread:

    as_integer = getattr(conn.r, 'as.integer')
    conn.r.sapply(conn.ref.List, as_integer)
    Out[8]: array([1, 2, 3], dtype=int32)