繁体   English   中英

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

[英]How to run a function contained in a R script, from Python ? The inputs for R function will be coming from Python

我正在使用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而不是命令行中完成此操作。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM