Question

I'm trying to make a simple call to a R package (ks) from within python through rpy2. This is what I would like to achieve:

import rpy2.robjects as robjects

# Define two matrices.
matrix1 = [[1,1,1,1], [3,3,3,3]]
matrix2 = [[1,1,1,1], [3,3,3,3]]

# Call 'ks' function to obtain p_value.
p_val = robjects.r('''
library(ks)
kde.test(x1=matrix1, x2=matrix2)$pvalue''')

print p_val

I tried following the documentation from rpy2 but it is very scarce. Any help would be appreciated.

Was it helpful?

Solution

Posting my own answer based on the one given by lgautier since that one did not work as is. I also made it a bit more general by passing nrow instead of having it fixed.

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
ks = importr('ks')

kde_test = ks.kde_test

matr1 = [1., 3., 1., 3., 0.2, 1.5, 0.5, 1.3]
matr2 = [1., 3., 1., 3., 0.2, 1.5, 0.5, 1.3, 0.5, 4.6]  

m1 = robjects.r.matrix(robjects.FloatVector(matr1), nrow=int(len(matr1)/2), byrow=True)
m2 = robjects.r.matrix(robjects.FloatVector(matr2), nrow=int(len(matr2)/2), byrow=True)

res = kde_test(x1 = m1, x2 = m2)

pval = res.rx2('pvalue')

print float(str(pval)[4:])

All credit goes to lgautier for proposing the solution even if it did not work at first.

OTHER TIPS

To get functions in packages:

from rpy2.robjects.packages import importr
ks = importr('ks')

kde_test = ks.kde_test

To build matrices:

import rpy2.robjects
Matrix = rpy2.robjects.r.matrix
from rpy2.robjects.vectors import IntVector
matrix1 = Matrix( IntVector([1,1,1,1, 3,3,3,3]), nrow=2)
matrix2 = Matrix( IntVector([1,1,1,1, 3,3,3,3]), nrow=2)

To call functions:

res = kde_test(x1 = matrix1, x2 = matrix2)

To extract a named element in a list:

pval = res.rx2('pvalue')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top