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

问题描述 投票:3回答:1

我正在使用Pycharm for Python。我在R中有一个名为'forecast.R'的脚本,其中包含一个函数 - > dummy_forecast(start_date,end_date),它在给定日期输出提前1周的预测。输出采用包含time_stamp和预测值的数据帧格式。我想从Python中指定脚本的输入,并将预测数据帧存储在Python中。

有没有办法在python中导入forecast.R脚本并调用函数dummy_forecast(),输入start_date和end_date存储在python中并输入到函数中?

rpy2包可用。但是,我们需要编写整个R脚本,这是冗余的,并且需要更多的Python脚本处理时间。

我需要在Pycharm而不是命令行中完成此操作。

python r pycharm forecasting
1个回答
1
投票

如果这个'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

© www.soinside.com 2019 - 2024. All rights reserved.