*R* Non-blocking console read in R - r

I am writing a tool in R having a crude CLI (Command Line Interface), which does non-blocking reads from a socket (that is working). I want to concurrently check for new commands, by reading a single character (if it exists) from the console in a non-blocking manner. A simplified example
repeat{
newCmdChar <- nonblockingReadConsole()
if (newCmdChar == NULL) doStuffReadingNonblockingSocket()
else switch(newCmdChar,
a = doThis(),
b = doThat(),
x = break)
}
Various experiments failed with file("stdin") in a nonblocking manner, and permutations on scan(), readLines() etc. One approach is described here How do you read a single character from console in R (without RETURN)? but it requires working through an open graphics device and I was hoping to avoid that.
Questions
is there any way to do nonblockingReadConsole() to get a single
character? If so, how?
better to explore some R GUI package? (I'm
a newbie, ignorant to those)? If so, suggestions?
Thanks :)
/george

I'm afraid that the answer is you probably can't get input from the R GUI command line in a non-blocking way. It goes against the single-threaded nature of R.
If you need this sort of behaviour, then write the human-interaction part in a different language and call R for the calculations. Or use one of the GUI toolkits, as described in the question you linked to.

Update: I've implemented the "open grDevice with keyboard callback" approach in the link cited above, and it is working out more conveniently than expected. Cheers, /geg

Related

R: Equivalent command to Matlab's keyboard function?

Does R provide a similar command for debugging like Matlab's keyboard?
This command provides an interactive shell and can be used in any function.
This gives access to all variables allowing one to verify that the input data is really what it should be (or test why it's not working as expected).
Makes debugging a lot easier (at least in Matlab...).
It sounds like you're looking for browser().
From the description:
A call to ‘browser’ can be included in the body of a function.
When reached, this causes a pause in the execution of the current
expression and allows access to the R interpreter.
It sounds like you're new to debugging in R so you might want to read Hadley's wiki page on debugging.
Have a look at ?recover, this function provides great debugging functionality.

ESS and RScript : Executing in style of `compile-dwim-run'

I just got ESS set up in EMACS (I'm a relative newbie in this area). I have figured out how to take an R script and fire up an interactive R shell and evaluate a whole buffer ("C-c C-b"). But I'd also like to have the ability to submit an R script via RScript in the way that you can with Perl or Python with `compile-dwim-run', which I have bound to "C-c r", and have the whole output returned to me in a separate buffer without keeping open an interactive R shell.
I can't seem to find a default way to do this, and I'd like to leverage whatever ESS has to work that (I assume there is) before I go off and attempt to roll my own.
Thank you,
Matt
C-c C-l is what you are looking for? Use C-c C-h to see all the keys that are bound on C-c map (an even better approach is to install helm-descrbind from emacs package manager - you will be pleasantly surprised :).
[edit:] Sorry, misread your post slightly. You want batch evaluation. That is not available for R. The reason, the analysis in R is usually a complex process which you don't want to execute again and again. So you keep your interactive session open and iteratively achieve what you want.
There have been talks inside ESS to add some batch functionality, but it seems like very few people really need that.

Can I move the cursor to revise in R?

I input something into the R console:
> ta <- function(x,y){
+ x=x+2
+ y=y+1
+
Now my cursor is on the fourth line, I found it's x=x+1, not x=x+2.
Can I move my cursor onto the second line to revise x=x+2 into x=x+1?
As far as I'm aware, you can't do what you describe. What you can do is press Esc to cancel entering into the console and start afresh writing it in.
Are you using an IDE? Or are you writing directly into the RGui? If the latter, I heartily recommend using RStudio. It will make your life a lot easier. You'll be able to to enter text into one window and then send it into the R console when you're ready.
Alternatively. R does have an editor (File > New script) which you can use to send lines, or you can even use a txt file off to the side and only send lines when you're ready.
AFAIK, there is no way to edit the function while R is still waiting for you to close the function call. So first, I think you need to finish writing your function by typing }. Once completed, you can then do one of a few things, all of which are outlined in good detail here. I won't bother regurgitating those perfectly good answers, but do recommend you check them out. Finally, if you aren't currently using an IDE to help develop your R code, that will make your life much easier. Which IDE will be best for you is also quite subjective, but has been covered on SO here before. FWIW, I've had good luck with RStudio which is platform independent and all that good jazz...your miles may vary.
If you are running R from a terminal, you can press ctrl + c to cancel your entry and start over.

plotting data in R from matlab

I was wondering if it is possible to work between matlab and R to plot some data. I have a script in matlab which generates a text file. From this I was wondering if it was possible to open R from within matlab and plot the data from this text file and then return to matlab.
For example, if I save a text file called test.txt, in the path 'E:\', and then define the path of R which in my case will be:
pathR = 'C:\Program Files\R\R-2.14.1\bin\R';
Is it possible to run a script already written in R saved under test1.R (saved in the same directory as test.txt) in R from matlab?
If you're working with Windows (from the path it looks like you are), you can use the MATLAB R-link from the File Exchange to pass data from Matlab to R, execute commands there, and retrieve output.
I don't use R so this is not something I have done but I see no reason why you shouldn't be able to use the system function to call R from a Matlab session. Look in the product documentation under the section Run External Commands, Scripts, and Programs for this and related approaches.
There are some platform-specific peculiarities to be aware of and you may have to wrestle a little with what is returned (though since you are planning to have R create a plot which is likely to be a side-effect rather than what is returned you may not). As ever this is covered quite well in the product's documentation
After using R(D)COM and Matlab R-link for a while, I do not recommend it. The COM interface has trouble parsing many commands and it is difficult to debug the code. I recommend using a system command from Matlab as described in the R Wiki. This also avoids having to install RAndFriends.

Switch R script from non-interactive to interactive

I've an R script, that takes commandline arguments, where the top line is:
#!/usr/bin/Rscript --slave
I wanted to interrupt execution in a function (so I can interactively use the data variables that have been loaded by that point to work out the next bit of code I need to write). I added this inside the function in question:
browser()
but it gets ignored. A bit of searching suggests it might be because the program is running in non-interactive mode. But even more searching has not tracked down how I switch the script out non-interactive mode so that browser() will work. Something like a browser_yes_I_really_mean_it() function.
P.S. I want to avoid altering the rest of the script if at all possible. My current approach is to copy and paste the code chunks, needed to prepare the data, into an interactive session; but as the script gets more and more complex this is getting more and more unreasonable.
UPDATE: for anyone else with the same question, it appears the answer to the actual question is that it is impossible. Once you start R in a non-interactive mode the die is cast. The given answers are therefore workarounds: either you hack your code (remembering to unhack it afterwards), or you refactor to make debugging easier. (This comment is not intended as a criticism of the answers; the suggested refactoring makes the code cleaner anyway.)
Can you just fire up R and source the file instead?
R
source("script.R")
Following mdsumner's answer, I edited my script like this:
if(!exists("argv")){
argv=commandArgs(TRUE)
if(length(argv)!=4)usage_and_exit()
}else{
if(length(argv)!=4){
stop("Must set argv as a 4 element vector. E.g. argv=c(...)")
}
}
Then no other change was needed, and I was able to do:
R
> argv=c('a','b','c','d')
> source("script.R")
In addition to the previous answer, I'd create a toplevel function (e.g. doStuff) which performs the analysis you want to perform in batch. The function takes the cmd line options as input. In the batch script you source the script that contains this function and call it. In this way you can easily run the function in interactive mode and use e.g. browser().
In some cases, the suggested solution (workaround) may not work - for example, when the R code needs to be run as a part of an existing bash script. For those cases, I suggest to write in your R script into the bash script using here document:
#!/bin/bash
R --interactive << EOT
# R code starts here
argv=c('a','b','c','d')
print(interactive())
# Rest of script contents
quit("no")
# R code ends here
EOT
This way, print(interactive()) above will yield TRUE.
Sidenote: Make sure to avoid the $ character in your R code, as this would not be processed correctly - for example, retrieve a column from a data.frame() by using df[["X1"]] instead of df$X1.

Resources