This will not only be platform dependent, but will depend on how you run R on your machine. I expect that it will differ depending if you are running the simple terminal version of R vs. running the R GUI that comes with R vs. running R through RStudio or another program like that.
It would also help if you could give more detail on what you are trying to accomplish? why you want to stop, or do something else within the script.
It may be possible to accomplish what you want by moving the focus to a new window that will watch for keyboard input and report it back to your script. For example, this answer: How to wait for a keypress in R? has code that will use the tcltk library to pop open a window and wait for a keypress or mouse click before continuing.
Here is some code that does more what you are suggesting:
library(tcltk)
evilglobalvariable <- NA
tt <- tktoplevel()
tkbind(tt, '<Key>', function(k) { evilglobalvariable <<- k})
for(i in 1:25) {
cat(i, "\n")
if(!is.na(evilglobalvariable)){
stop('A key was pressed')
}
Sys.sleep(1)
}
This will stop the loop if you press any key while the Tk window is active. But it will not detect other key presses, e.g. if you open your email program and compose a message, those key presses will not stop the loop.
If you are going to do anything serious with this it would be better to use a specific environment rather than the evil global variable.