How to Interrupt a Running Code in R with a Keyboard Command

How to stop a command in R in Windows

When running a code, the red octagon will only show while it is working things out. So while it is just running through your written code (reading data and names of things etc) then the octagon will not show.

Pressing ESC will work, unless Rstudio is frozen.

Good luck!

Make execution stop on error in RStudio / Interactive R session

I don't think that there is a way to prevent RStudio from running all the lines, when you select a section and press Ctrl+Enter. Rstudio is just running one line after the other. Even if stopifnot() is called inside of a function, all the lines after that function call will still be evaluated.

If your goal is simply to be informed when something goes wrong, before a lot of code is run in vain, maybe you could define a function similar to stopifnot() that will just go into an endless loop, if there is an error. You could then press Esc or the Stop-Button in RStudio to interrupt the program. Something like this:

waitifnot <- function(cond) {
if (!cond) {
message(deparse(substitute(cond)), " is not TRUE")
while (TRUE) {}
}
}

Now, you can run your example code with this function:

x <- 'test'
waitifnot(is.numeric(x))
print('hello world')

As expected, hello world is never printed. You will get an error message, telling you that something went wrong, and then the program will wait until you abort it manually.

This won't work well in any situation other than interactive mode. To avoid unpleasant situations, you could also let the function react differently, if it is not used in interactive mode, for instance like this:

waitifnot <- function(cond) {
if (!cond) {
msg <- paste(deparse(substitute(cond)), "is not TRUE")
if (interactive()) {
message(msg)
while (TRUE) {}
} else {
stop(msg)
}
}
}

This function will go into an endless loop only if run in interactive mode. Otherwise, it will simply abort execution by calling stop(). I have checked that this works as expected with Ctrl+Enter or the Source button in RStudio (endless loop) and with Rscript on the Bash command line (abort of the program).

Break loop with keyboard input (R)

Suggestion 1: TCL/TK

library(tcltk)
win1 <- tktoplevel()
butStop <- tkbutton(win1, text = "Stop",
command = function() {
assign("stoploop", TRUE, envir=.GlobalEnv)
tkdestroy(win1)
})
tkgrid(butStop)

stoploop <- FALSE
while(!stoploop) {
cat(". ")
Sys.sleep(1)
}
cat("\n")

Some code borrowed from: A button that triggers a function call.

Suggestion 2: Non-blocking checking on standard input. (Please be warned: C is not my core competence, and I cobbled this together from bits on the internet.) The main idea is to write a function in C that waits for user input, and call it from R.

Snippet below adapted from Non-blocking user input in loop. Save the following code as kbhit.c:

#include <stdio.h>
#include <unistd.h>
#include <R.h>

void kbhit(int *result)
{
struct timeval tv;
fd_set fds;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds); //STDIN_FILENO is 0
select(STDIN_FILENO+1, &fds, NULL, NULL, &tv);
*result = FD_ISSET(STDIN_FILENO, &fds);
}

Then, from the command line, run R CMD SHLIB kbhit.c to compile it for R.

Finally, in R, load the newly created kbhit.so, write a function (kbhit) that returns the output from the C function, and then run your loop. kbhit() returns 0 unless it receives the enter key. Note that the only way to stop the loop is by hitting enter/return (or a hard break) -- if you want a more flexible approach, see the link above.

dyn.load("kbhit.so")

kbhit <- function() {
ch <- .C("kbhit", result=as.integer(0))
return(ch$result)
}

cat("Hit <enter> to stop\n")
while(kbhit()==0) {
cat(". ")
Sys.sleep(1)
}

More details on the .C interface to R.

On a Windows machine:

kbhit.c

#include <stdio.h>
#include <conio.h>
#include <R.h>

void do_kbhit(int *result) {
*result = kbhit();
}

In R:

dyn.load("kbhit.dll")

kbhit <- function() {
ch <- .C("do_kbhit", result=as.integer(0))
return(ch$result)
}

cat("Hit any key to stop\n")
while(kbhit()==0) {
cat(". ")
Sys.sleep(1)
}

P.s. I hacked this together through Googling, so unfortunately I don't know how or why it works (if it works at all for you!).

What exactly does the stop button in R do?

The "stop button" is actually a GUI feature so its documentation should be consulted. The keyboard ctrl-C or 'esc-key' should do the same. The commentary I have seen is rather non-committal about how soon an interrupt will be handled. It says something like: "well written code will handle interrupts promptly."

> x=1:1000000
> i=2
> repeat{
+ x[i]=x[i]+3
+ x[i-1]=x[i]+1
+ i=i+1
+ if(i>length(x)){break} } # esc key hit promptly
> i
[1] 15128

You should read the help page for:

?conditions

The 'R for Mac OS X FAQ' says: "However, if the executed code does not check for interrupts (using `R_CheckUserInterrupt') there may be no way of stopping R. In that case it may be worth alerting the maintainer of the package to allow interruption (if appropriate)."

This search will let you page through postings to R-devel that mention that internal mechanism by name: http://markmail.org/search/?q=list%3Aorg.r-project+R_CheckUserInterrupt



Related Topics



Leave a reply



Submit