【发布时间】:2016-05-25 18:21:40
【问题描述】:
我正在尝试在 python 中访问 'midasr' 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 中成功运行相同的数据集。
有人知道如何解决这个问题吗?非常感谢!
【问题讨论】: