Pass list from python to R through rpy2

坚强是说给别人听的谎言 提交于 2019-12-06 07:18:38
Gabriel

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.

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