通过rpy2

时间:2017-05-07 08:40:32

标签: python r rpy2

我在Python中使用R的spi函数。其中一个参数(“内核”)需要一个列表,我不确定在使用rpy2时如何通过它。 R语法如下( with “kernel”参数):

library("lmomco", lib.loc="~/lib/R_libs")
library("SPEI", lib.loc="~/lib/R_libs")

data = read.csv("rainfall_data.csv", header = FALSE)
result = spi(data, scale=10, distribution='Gamma', fit='max-lik', kernel = list(type='rectangular', shift=0))

到目前为止我的Python脚本(没有使用“kernel”参数)如下:

import numpy as np 
from rpy2.robjects.packages import importr
importr('lmomco')
SPEI = importr('SPEI')

import rpy2.robjects.numpy2ri as numpy2ri
numpy2ri.activate()

data = np.genfromtxt('rainfall_data.csv', delimiter=',')

result = np.array(SPEI.spi(data, scale=10, distribution='Gamma', fit='max-lik')[1])

如何将内核作为rpy2的列表传递?

1 个答案:

答案 0 :(得分:2)

考虑从python字典创建ListVector,然后将其传递给方法:

import rpy2.robjects as robjects 
...
x = robjects.ListVector({'type': 'rectangular', 'shift': 0})

result = np.array(SPEI.spi(data, scale=10, distribution='Gamma', fit='max-lik', kernel=x)[1])