Take the 2-minute tour ×

I am a newbie. I've an R file ,containing a function with a parameter. I' d like to perform the two following distinct operations:

  1. Run the function
  2. Execute step by step and debug it

suppose to have a simple function in an R file


Could you tell me which are R commands to perform what I asked.

share|improve this question
Don't forget to read the help pages of ?debug and ?browser very carefully. –  Joris Meys Dec 29 '10 at 14:09
I altered the title of the question to remove confusion with Rscript which is an entirely different beast –  JD Long Dec 29 '10 at 16:57
add comment

2 Answers

You have to call debug(<functionName>) to step through a function. The next time you call the function, the so-called browser environment will automatically be opened and list the content of your function. You perform one step by pressing Return or with the n command (next). A single step is one block (usually a single line) that will be listed before it's run. To run the function to its end, press c (continue). When you're in browser mode, you can use ls(), str(), class(), ... to inspect the objects. Your example looks like this:

> exampleSum <- function(x, y) {
+   x <- x+1
+   return(x+y)
+ }

> debug(exampleSum)             # set debug flag
> exampleSum(1, 2)              # run function in browser mode
debugging in: exampleSum(1, 2)
debug: {
    x <- x + 1
    return(x + y)
Browse[2]> n                    # next step
debug: x <- x + 1
Browse[2]> ls()                 # show objects
[1] "x" "y"
Browse[2]> x                    # show x
[1] 1
Browse[2]> c                    # run function to end
exiting from: exampleSum(1, 2)
[1] 4

> undebug(exampleSum)           # remove debug flag

The last call to undebug(<functionName>) removes the debug flag from the function such that it will be run normally the next time it's called.

share|improve this answer
debugonce is also helpfull when you need only one-time check. –  Marek Dec 29 '10 at 11:22
what if you want to run the next 100 lines? –  qed Feb 16 '12 at 7:36
add comment

You first need to load the function into R's workspace (by copy/pasting it to R). Then, you can run it using exampleSum(x = 1, y = 1). You can check that it's there by typing exampleSum into R console. You can also run the script file using source(). Example of usage would be source("d:/R/my_script.R").

I think you would benefit immensely by reading at least An Introduction to R. There is also a plethora of books available to R beginners that explain the very basics. Equivalent information is available in the aforementioned AI2R and free materials floating around the internet. Searching the R help list is also... helpful.

share|improve this answer
add comment

Your Answer


