gpt4 book ai didi

python - 执行 R 脚本后获取结果到 python 变量

转载 作者:太空宇宙 更新时间:2023-11-04 01:04:06 46 4
gpt4 key购买 nike

我正在从 python 执行一个 r 脚本,我希望输出在 python 变量中可用。我该怎么做?

python 脚本:

import subprocess 

def runR(id, lat, long):
value = subprocess.popen("C:/R/R-3.2.0/bin/Rscript E:/Personal/python/script.R --args "+id+" "+lat+" "+long , shell=True)
print value

R 脚本:

a = "Hello";

我希望 Hello 在 python 变量值上可用。

最佳答案

你可以使用 rpy2 :

import rpy2.robjects as robjects

robjects.r('''
a = "Hello";
''')
a = robjects.r['a']

作为替代方案,您可以重写您的 R 脚本,以便它将其结果以某种众所周知的格式(例如 json)转储到标准输出,然后使用 subprocess 模块运行它,并解析结果:

#!/usr/bin/env python
import json
import subprocess

id, lat, long = 1, 40, 74
out = subprocess.check_output(r"C:\R\R-3.2.0\bin\Rscript.exe "
r"E:\path\to\script.R --args "
"{id} {lat} {long}".format(**vars()))
data = json.loads(out.decode('utf-8'))

注意:如果您在此处使用可执行文件的完整路径,则无需在 Windows 上使用 shell=True

关于python - 执行 R 脚本后获取结果到 python 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31386728/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com