python - 如何从 Python 运行 R 脚本中包含的函数? R 函数的输入将来自 Python

标签 python r pycharm forecasting

我正在使用适用于 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/

相关文章:

使用 "pathlib.Path"寻址 BASE_DIR 时,django Pycharm 2020.2.2 无法解析静态文件

python - 如何根据时间段评估日志跟踪

python - Django 模型外键无法识别 'QueryString' BaseObject

r - 聚集在前两行

r - 每行删除重复项的整洁方法

templates - PyCharm中自动填充文件 "creation"日期

python - 如何让 PyC​​harm/PyDev/其他 IDE 为 IronPython 命名空间提供代码补全?

python - 如果外键不存在,SQLAlchemy 会自动创建条目

python - 每当 matplotlib 中两条线相遇时,如何使用 Python 打印某些内容?

r - R 中的多个直方图