[R] Executing a code until a new user input aborts it (readlines?)

Greg Snow
Mon, 16 Sep 2013 16:45:55 -0000

Here is one approach that uses the tcltk package to create a button on a
different loop than yours, clicking the button will change a variable
(ShouldIStop) in a temporary environment that both your look and the tk
 button can access.  The loop then just checks the variable from time to
time and if it is now true then it breaks out of the loop:

library(tcltk)

tmpenv <- new.env()

tt <- tktoplevel()
tkpack( tkbutton(tt, text='Stop',
  command=function() tmpenv$ShouldIStop <- TRUE))

tmpenv$ShouldIStop <- FALSE

i <- 1

repeat {
  cat(i)
  flush.console()
  Sys.sleep(2)
  i <- i + 1
  if( tmpenv$ShouldIStop ) {cat('\n\n');break}
  cat('\r')
}



On Sun, Sep 15, 2013 at 3:42 AM, Hadassa Brunschwig <
hadassa.brunschwig@mail.huji.ac.il> wrote:

> Hi,
>
> I know that with readlines you can start executing a code upon user input.
> What I would like to do is to have the ability to abort a code based on a
> new user input. E.g. when the user hits enter the code stops running. That
> is, I would periodically check for a user input and stop the code when the
> correct input was entered.
>
> Below is an example of a function which would run an endless loop but check
> in each iteration if there was a new user input which would abort it. It
> does not do the right thing obviously but maybe someone can point out how
> this can be done.
>
> startSystem <- function(){
>
>     cat("Processing code, hit ENTER to stop.")
>     i=a=n=1
>     while(!is.na(n)){
>       a=i+a
>       i=i+1
>       n = readline("")
>     }
>     return(NULL)
>
> }
>
> Thanks!
>
>         [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



--
Gregory (Greg) L. Snow Ph.D.
538280@gmail.com

	[[alternative HTML version deleted]]