0

Is there a way to access the keyboard buffer in R? I suspect that it is platform dependent, and so for what it is worth, I'm using Windows 10.

Specifically, I want to check whether something (anything) has been pressed on the keyboard at a specific point in my code, and if it has, do something, else continue. For example:

### stuff here
if(!is.na(KEYBOARD_BUFFER)){  ### or !is.null, etc.
  stop("Someone pressed something!")
}
### stuff continues here

Thank you in advance.

bioniclime
  • 47
  • 5
  • 1
    This is for sure platform dependent according to [this answer](https://stackoverflow.com/a/5322809/8386140) to a similar question in the context of C. Since you can call C code from R, you could probably adapt that answer for your needs. – duckmayr Sep 17 '18 at 15:19

1 Answers1

0

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.

Greg Snow
  • 48,497
  • 6
  • 83
  • 110