在python中通过rpy2使用midasr r包函数时出错

时间:2016-05-25 18:21:41

标签: python r pandas rpy2

我正在尝试访问& amas'在python中使用r包,这是我的代码:

from rpy2.robjects import pandas2ri
pandas2ri.activate()
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
import pandas as pd

....
base = importr('base')
stats = importr('stats')
midasr = importr('midasr')

x = np.random.rand(11256)
y = np.random.rand(1407)
eq = midasr.midas_r('y ~ mls(x, 0:15, 8, nealmon)', start = 'list(x = c(0, 0))')

我收到错误:

RRuntimeError: Error in new.env(parent = environment(formula)) : 
  use of NULL environment is defunct

它在R中起作用:

eq_r <- midas_r(y ~ mls(x, 0:15, 8, nealmon), start = list(x = c(0,0)))

所以我尝试了另一种方法:

temp = np.empty(len(x))
temp[:] = np.nan
temp[0:1407] = y
dataframe = pd.DataFrame({'x': x, 'y': temp}) 
rdf = pandas2ri.DataFrame(dataframe)
robjects.globalenv['dataframe'] = dataframe
eq = midasr.midas_r('y[1:1407] ~ mls(x, 0:15, 8, nealmon)', data=rdf, start = 'list(x = c(0, 0))')

仍然是同样的错误。

在我收到@Parfeit的回复后,我尝试了:

formula = robjects.Formula('y_ro ~ mls(x_ro, 0:15, 8, nealmon)')
env = formula.environment
env["y_ro"] = y_ro
env["x_ro"] = x_ro
slist = robjects.ListVector({'x_ro': robjects.IntVector((0, 0))})
eq = midasr.midas_r(formula, start = slist)

但现在我明白了:

RRuntimeError: Error in midas_r.fit(prepmd) : 
  The optimisation algorithm of MIDAS regression failed with the following message:
Error in y - mdsrhs(p) : non-conformable arrays

Please try other starting values or a different optimisation function

但是我可以在r中成功运行相同的数据集。

任何人都知道如何解决这个问题?非常感谢!

2 个答案:

答案 0 :(得分:1)

考虑构建公式,使用传入的Python对象传递当前值和start参数:

x = np.random.rand(11256)
y = np.random.rand(1407)

formula = robjects.Formula('y ~ x')
env = formula.environment
env["y"] = y
env["x"] = midasr.mls(x, robjects.IntVector(range(15)), 8, midasr.nealmon)    # MLS() FCT

slist = robjects.ListVector({'x': robjects.IntVector((0, 0))})                # R LIST: $x [1] 0 0

eq = midasr.midas_r(formula, start = slist)

答案 1 :(得分:0)

使用与Parfait相同的代码,并添加具有正确数量的元素(等于变量数量)的start参数

 x = np.random.rand(11256)
 y = np.random.rand(1407)

 formula = robjects.Formula('y ~ x')
 env = formula.environment
 env["y"] = y
 env["x"] = midasr.mls(x, robjects.IntVector(range(16)), 8, midasr.nealmon)# MLS() FCT

 slist = robjects.ListVector({'x': robjects.IntVector(base.rep(0,16))})# R LIST: $x [1] 0 0

 eq = midasr.midas_r(formula, start = slist)