我正在使用适用于 Python 的 Pycharm。我在 R 中有一个名为“forecast.R”的脚本,其中包含一个函数 -> dummy_forecast(start_date, end_date),它输出给定日期的提前 1 周预测。输出采用包含时间戳和预测值的数据帧格式。我想指定从 Python 到脚本的输入,并将预测数据帧也存储在 Python 中。
有什么方法可以在 python 中导入 forecast.R 脚本并调用函数 dummy_forecast(),输入 start_date 和 end_date 存储在 python 中并输入到函数中?
rpy2 包可用。然而,我们需要编写整个 R 脚本,这对于 Python 脚本来说是多余的并且需要更多的处理时间。
我需要在 Pycharm 中而不是在命令行中完成。
最佳答案
如果这个“R”脚本是用 python 编写的,您可以编辑该函数以在其运行结束时返回预测,然后当您在主脚本中调用该函数时,您可以为其分配一个变量,因此例如:
脚本 R:
def dummy_forecast(s, e):
#do calculations etc
return forecast #or whatever you have called the data stored in here.
主要脚本:
#as long as script R is in the same folder as the main script, you can just do:
import R
#if it is not, this is what you want to do:
import sys
sys.path.insert(0, r'C:\directory\of\script\r')
import R
#then once you have imported R, you can do the following
start = 'blah blah'
end = 'blah blah'
forecast = R.dummy_forecast(start, end)
print forecast
关于python - 如何从 Python 运行 R 脚本中包含的函数? R 函数的输入将来自 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55531603/