32

I've been playing a little bit with R Markdown and I really like it, because after each of my analyses I need to write a (Word) report detailing the results. With R Markdown, the code and report are the same document, so it's easy to remember that I chose to perform analysis B at a certain point in the code, because of the results of analysis A before.

However, I'm not able to set breakpoints in R Markdown inside R Studio, and this limits severely the possibility of performing efficient debugging. This implies that in the end I can only use Markdown for very trivial analyses, where the R code is so simple that either I don't have to debug it, or I can debug it manually. It this to be expected, i.e., is it well-known that R Markdown can only be used for simple analyses? Or is there a solution?

1
  • 4
    I don't get the reason for the downvote. The question is clear: I cannot set breakpoints in R Markdown (or at least I'm not able to) using R Studio. So how do I debug complex code in R Markdown? Commented Mar 16, 2017 at 6:57

2 Answers 2

22

You can use browser() in your code to set breakpoints. See https://support.rstudio.com/hc/en-us/articles/205612627-Debugging-with-RStudio#debugging-in-r-markdown-documents

I've find it more useful to write custom functions in a .R and source() it in Markdown. Then, you get the best of both worlds.

Sign up to request clarification or add additional context in comments.

3 Comments

In R Markdown I usually have many chunks. Are you suggesting to write one custom function for each chunk? If the result of one function depends on a function in another chunk, it seems that debugging would get complicated.
No, I usually write all the functions I'm using in a few .R files (e.g., one for common custom functions I reuse in many analyses, and one for custom functions I wrote for this particular analysis), source the files in the first chunk, and use the functions in subsequent chunks.
While I support the validity of this answer - i.e. "don't shoot the messenger" - this RMarkdown is inferior to a jupytext / jupyter approach in which the same file can either be debugged as a fully- baked self-contained script or drive a notebook interaction. I prefer the R language but RMarkdown is going to be awkward
2

You can generate Word and other reports from normal R scripts using knitr::spin in combination with special roxygen2-style comments. Then you can run your script and use breakpoints as normal.

https://rmarkdown.rstudio.com/articles_report_from_r_script.html

There's also a toolbar button in RStudio to do this.

1 Comment

Indeed. This makes debugging easier. I'd say for R code heavy reports I'd prefer using .R files with special comments, and for text heavy reports I'd use .Rmd

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.