【问题标题】:Change R Script variables in Python, then Save back to R Script在 Python 中更改 R 脚本变量,然后保存回 R 脚本
【发布时间】:2014-04-10 23:39:25
【问题描述】:

我想将 R 脚本文件读入 Python(使用 Tkinter GUI 包)并更改一些变量(或者只是打印并使用它们),然后将这些变量重新保存回 R 脚本文件。我正在查看 Rpy2 模块,但我没有看到任何可以帮助我完成它的东西。我要更改的变量是字符串和数字变量(在 R 中)。

例如:

R 脚本包含:

eventtime<-"18:30:00"   
eventdate<-"2014-02-28" 

Python 文件:

import Tkinter as tk
from rpy2.robjects import r

class GUI(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master, width=300, height=200)
        self.master = master
        self.master.title('GUI')

        self.pack_propagate(0)
        self.pack()

        self.run_button = tk.Button(self, text='Run', command=self.evaluate)
        self.run_button.pack(fill=tk.X, side=tk.BOTTOM)

        self.entrybox_frame = tk.Frame(self)
        self.entrybox_frame.pack(anchor=tk.S, pady=5)

        self.eventtime_var = tk.StringVar()
        self.eventtime = tk.Entry(self.entrybox_frame, textvariable=self.eventtime_var)
        self.eventdate_var = tk.StringVar()
        self.eventdate = tk.Entry(self.entrybox_frame, textvariable=self.eventdate_var)

        self.eventtime.grid(row=0, column=1)
        self.eventdate.grid(row=1, column=1)

    def evaluate(self):
        # Clicking the Run button will save the variables to the R script
        r.source('file.r')
        self.get_event_info()

    def run(self):
        self.mainloop()

    def get_event_info(self):
        # Get the user input and write them to the R variables
        # So first must read the R script into python, then rewrite over those variables 
        # Then save the R script
        print self.eventtime_var.get()
        print self.eventdate_var.get()

gui = GUI(tk.Tk())
gui.run()

有什么想法吗?

【问题讨论】:

  • 没有示例很难帮助您?为什么不在 R 中这样做?
  • 所以本质上我正在使用 Tkinter 创建一个 GUI,用户在其中输入一些变量,我想将这些变量保存到 R 脚本,然后调用 rpy2.robjects.r.source('filename ') 在 Python 中,它执行另一组操作。
  • 请添加您的脚本示例和您要更改的变量。
  • 在我看来,您重写的目的是调整变量并再次运行 R 脚本,对吗?为什么不使用带有位置参数的 Rscript 解释脚本作为变量?
  • 是的,这是正确的。我不确定你对 Rscript 的意思。

标签: python r rpy2


【解决方案1】:

与其将变量硬编码到脚本中,不如使用将它们作为 Rscript 中的位置参数传递,或者在获取脚本(需要它们)之前在 R 环境中设置它们。

用位置参数解释 R 脚本

关于 passing arguments (as your variables) 要编写脚本,您可以在 SO 上找到一些已经回答的问题。 上面的链接只是一个开始。

R-intro B.4 Scripting with R 是官方来源。

Rpy2 在 R 环境中更改对象

您可以在获取 rscript 之前在 R 环境中设置或更改 (by Rpy2 means) 变量,这将使用已经设置的变量,因此必须准备好脚本,不要设置它们,而只是使用它们。

【讨论】:

  • 我将如何在我的 Python 应用程序中实现 Rscript?我不必在 Rscript 中使用命令行吗?
  • Rscript 是解释器,通常从终端启动。为什么需要python?为用户提供接口?我相信你需要的所有东西都可以直接从 R 中穿上。
  • 所以我不想启动终端,我希望我的 Python 应用程序中的所有内容都是独立的,这就是我研究 Rpy2 的原因。
  • 我明白了。然后你将不得不搜索如何从 Rpy2 修改 R 环境而不是重写脚本。
  • 谢谢!是的,我刚刚在 Python 中分配了“R 变量”,然后获取了 R 脚本。如您所说,它在 R 环境中使用这些变量。
【解决方案2】:

rpy2 通过将 R 脚本封装到 Python 端的命名空间和 R 端的环境中,提供了一种更好的方法来处理 R 脚本。

检查relevant section of the rpy2 documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-01
    • 2020-02-16
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-30
    相关资源
    最近更新 更多