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.)
You can run R interactively or in batch mode. e.g. type in R from the shell. The window that appears is called the R console. Any command you type into the prompt is interpreted by the R kernel.
Details. An interactive R session is one in which it is assumed that there is a human operator to interact with, so for example R can prompt for corrections to incorrect input or ask what to do next or if it is OK to move to the next plot. GUI consoles will arrange to start R in an interactive session.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With