I wonder if anyone knows how to debug R script in a linux environment using command line. For example, in python we can use pdb. We first set a break point (pdb.set_trace()), we then can use command like 'c','n','s','b', etc. to debug the python code in the linux environment. I have been searching lots of information for R debugging, but so far I did not find a similar function in R. Thank you very much for your help!
Asked
Active
Viewed 2,989 times
5
-
When you say "command line" do you mean you're running the script via something like `Rscript file.R`, or do you mean you're calling `source()` from within R? – joran May 24 '18 at 21:34
-
1If the former (`Rscript`), I think the answer is unfortunately `cat` (or `message` or `warning` or some form of logging). If on the R console (`Rterm`, RStudio, or similar), consider http://adv-r.had.co.nz/Exceptions-Debugging.html – r2evans May 24 '18 at 21:35
-
@joran, I mean use Rscript file.R. – Tong Qiu May 24 '18 at 21:42
-
@r2evans, thanks, let me take a look. – Tong Qiu May 24 '18 at 21:42
-
1If your normal use is `Rscript`, then your "`pdb`-equivalent" is `R`. R's debugging support is "just okay" but not on the same level as `pdb`, `gdb`, or debugging techniques available for many programming languages/environments. – r2evans May 24 '18 at 22:28
-
Maybe http://www.math.ncu.edu.tw/~chenwc/R_note/reference/debug/Rdebug.pdf helps – zhaofeng-shu33 Aug 14 '19 at 09:27
1 Answers
0
There's no native way to debug Rscript in the command line, but you can use a kind of hacky workaround I whipped up with readLines
and eval
.
ipdb.r <- function(){
input <- ""
while(!input %in% c("c","cont","continue"))
{
cat("ipdb.r>")
# stdin connection to work outside interactive session
input <- readLines("stdin",n=1)
if(!input %in% c("c","cont","continue","exit"))
{
# parent.frame() runs command outside function environment
print(eval(parse(text=input),parent.frame()))
}else if(input=="exit")
{
stop("Exiting from ipdb.r...")
}
}
}
Example usage in an R file to be called with Rscript:
ipdbrtest.R
a <- 3
print(a)
ipdb.r()
print(a)
Command line:
$ Rscript ipdbrtest.R
[1] 3
ipdb.r>a+3
[1] 6
ipdb.r>a+4
[1] 7
ipdb.r>a <- 4
[1] 4
ipdb.r>c
[1] 4
I would encourage anybody using this to expand upon it for greater debugging functionality.

jpd527
- 1,543
- 1
- 14
- 30