Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you read a single character from console in R (without RETURN)?

Tags:

r

Just started using R. Like with any language, I want to be able to step though a program interactively and quickly.

I usually write something like (pseudo code)

get_char(char)
if (char == 'q') {return}
if (char == 'a') {list.append(blah)}
if (char is anything else) {just move along}

q is for quit and a is for append and they are both right under my left hand on the keyboard so this is as fast as possible.

I see in R I can use

char=readline("Type a character and hit Enter")

but of course I have to hit enter. Is there a way of just getting a character in R?

like image 734
Dave31415 Avatar asked Oct 29 '25 03:10

Dave31415


1 Answers

Not a direct answer to your question, but you could use debug to get the behaviour you want. If you have a function you want to test, calling debug(myfunction) sets up R's debugger, so that when you next call myfunction() it is executed one line at a time. If you hit enter inside the debugger, it steps through to the next line of the function. If you want to examine any of the data in scope for the function, or run any other arbitrary R code, you can do that too, as the debugger provides access to all the regular R functions.

Not quite what you want to do with prompting for a single character from the user, but for debugging I think this is much more powerful.

like image 195
Tyler Avatar answered Oct 31 '25 16:10

Tyler