Search code examples
rrstudioprompt

Prompt to put input string to variable - R


I am running an R script daily that I would like to prompt me to enter data when selecting all the whole script.

I have already tried readline(prompt = ), which prompts in the rstudio console, but it does not prompt me if I select all code to run. I also did not like the prompt being in the console because it was easy to overlook.

I have also looked into library(tcltk), in hopes that a message box could help, but nothing I tried seemed to work.


Solution

  • Here's a method using library(tcltk)

    EntryBox <- function(label = 'Enter', title = 'Entry Box') {
        tt <- tktoplevel()
        tkwm.title(tt, title)   
        done <- tclVar(0)
        tkbind(tt,"<Destroy>", function() tclvalue(done) <- 2)
        result <- tclVar("")
        cancel.but <- tkbutton(tt, text='Cancel', command=function() tclvalue(done) <- 2)
        submit.but <- tkbutton(tt, text="Submit", command=function() tclvalue(done) <- 1)
        tkgrid(tklabel(tt, text=label),  tkentry(tt, textvariable=result), pady=3, padx=3)
        tkgrid(submit.but, cancel.but, pady=3, padx=3)
        tkfocus(tt)
        tkwait.variable(done)
        if(tclvalue(done) != 1) result <- "" else result <- tclvalue(result)
        tkdestroy(tt)
      return(result)
    }
    
    x <- EntryBox(label = 'Enter a string'); x