通过 rpy2 将列表从 python 传递到 R [英] Pass list from python to R through rpy2
本文介绍了通过 rpy2 将列表从 python 传递到 R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试通过 rpy2.这就是我想要实现的目标:
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
我尝试遵循 rpy2 的文档 但它非常稀缺.任何帮助将不胜感激.
I tried following the documentation from rpy2 but it is very scarce. Any help would be appreciated.
推荐答案
根据 lgautier给出的答案发布我自己的答案a> 因为那个没有按原样工作.我还通过传递 nrow
而不是固定它来使它更通用.
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:])
所有的功劳都归功于 lgautier 提出的解决方案,即使它一开始没有奏效.
All credit goes to lgautier for proposing the solution even if it did not work at first.
这篇关于通过 rpy2 将列表从 python 传递到 R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文