Madcat
Madcat

Reputation: 379

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).

Upvotes: 0

Views: 352

Answers (2)

Tushar
Tushar

Reputation: 24

A more productive way of handling this is to use the R function call syntax in Python provided by pyRserve instead of wrapping the whole R expression in a string and running it using eval.

'pyRserve' allow you to call R functions directly by using function syntax like conn.rfunction_name

Upvotes: 0

Madcat
Madcat

Reputation: 379

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)

Upvotes: 0

Related Questions