How do you read a single character from the console in R (without RETURN)?
Just started using R. As with any language, I want you to be able to quickly and quickly execute the program interactively.
I usually write something like (pseudocode)
get_char(char)
if (char == 'q') {return}
if (char == 'a') {list.append(blah)}
if (char is anything else) {just move along}
q for quit and a for append, and they are under my left hand on my keyboard, so this is as fast as possible.
I can see in R, I can use
char=readline("Type a character and hit Enter")
but of course I need to hit enter. Is there a way to get a character in R?
source to share
Not a direct answer to your question, but you can use debug
to get the behavior you want . If you have a function that you want to test, the call debug(myfunction)
sets up the R debugger, so the next call myfunction()
executes one line at a time. If you hit enter inside the debugger, it will jump to the next line of the function. If you want to examine any of the data in the scope of a function, or run any other arbitrary R code, you can do that as well, since the debugger provides access to all the regular R functions.
Not exactly what you want to do with a single character request from the user, but for debugging purposes I think it is much more powerful.
source to share
One way to do this is shown in the function sudoku::playSudoku
. On windows, the function getGraphicsEvent
provides a callback for keyboard input; on other devices you can use the Tk widget.
However, the graphics device must be open.
Here's an example for windows:
dev.new()
getGraphicsEvent(
"",
onKeyb=function(x)
if(tolower(x)=="q")
return(1)
else
cat("you pressed a key.\n")
)
source to share