2

I'm trying to use R for a data input task. I make a plot, decide whether it's type 1, 2, or 3, and hit the corresponding key on my laptop. What I'd like to do is avoid needing to hit enter after each one and simply have R progress to the next plot.

Here's a reprex for what I'm doing right now. For the most part, it works great - it collects my inputs, moves to the next plot, and returns them as an object when I'm done.

replicate(10, {
  plot(runif(10))
  readLines(n = 1)
})

However, I have to use twice as many keystrokes because I'm hitting Enter after each entry and it's annoying. For a lot of data, this is tedious and error-prone.

Is there a way to read exactly one character from R's stdin()?

It seemed like readChar(stdin(), nchars = 1) would do exactly what I wanted, but I get an error instead:

Error in readChar(stdin(), nchars = 1) : 
  'read' not enabled for this connection

My next solution will be using AutoHotKey or something to send "1\n" to the console but I'm hoping for an R-exclusive solution first. There's a popular C++ solution here and I'm open to Rcpp ports but those feel like overkill for a problem like this.

Dubukay
  • 1,764
  • 1
  • 8
  • 13
  • 1
    Does this answer your question? [How do you read a single character from console in R (without RETURN)?](https://stackoverflow.com/questions/9980512/how-do-you-read-a-single-character-from-console-in-r-without-return) – Konrad Apr 16 '22 at 09:43
  • If you're running R in a terminal, you can use the `keypress` package. See https://github.com/gaborcsardi/keypress#Support – Caspar V. Apr 16 '22 at 14:18
  • `keypress` written in `C`, that I guess the `C++` would be wrapping. Replace readLines with keypress() and perhaps fully automate plot type [1:3] process with BrailleR. – Chris Apr 16 '22 at 16:01
  • Well, the `BrailleR` package is conveying graph annotations, like title & etc. What do your [1:3] signify? – Chris Apr 16 '22 at 17:50
  • Are you open perhaps to a solution using `shiny` package? – jpdugo17 Apr 16 '22 at 20:50

0 Answers0