Question

I want to read in an R script file into Python (using Tkinter GUI package) and change some of the variables (or just print and play around with them), then re-save those variables back into the R script file. I am taking a look at the Rpy2 module, but I don't see anything in there that will help me accomplish that. The variables that I want to change are string and numeric variables (in R).

For example:

R Script contains:

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

Python file:

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()

Any ideas?

Was it helpful?

Solution

Rather than hardcoding variables into script is better to use passing them as possitional arguments in Rscript or setting them in R environment before the script (which needs them) is sourced.

Interpreting R scripts with positional erguments

Regarding passing arguments (as your variables) to script, you can find some already answered questions on SO. The above link is just a starter.

R-intro B.4 Scripting with R is the official source.

Rpy2 Changing objects in R environment

You could set or change (by Rpy2 means) variables in R environment before sourcing the rscript, which will use already set variables, so the script must be prepared not to set them but just use them.

OTHER TIPS

rpy2 offers a possible better way to handle an R script by encapsulating it into in namespace on the Python end, and in an environment on the R end.

Check the relevant section of the rpy2 documentation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top