How to Request an Early Exit When Knitting an Rmd Document

How to request an early exit when knitting an Rmd document?

To exit early from the knitting process, you may use the function knitr::knit_exit() anywhere in the source document (in a code chunk or inline expression). Once knit_exit() is called, knitr will ignore all the rest of the document and write out the results it has collected so far.

There is no way to tolerate errors in inline R code at the moment. You need to make sure inline R code always runs without errors1. If errors do occur, you should see the range of lines that produced the error from the knitr log in the console, of the form Quitting from lines x1-x2 (filename.Rmd). Then you can go to the file filename.Rmd and see what is wrong with the lines from x1 to x2. Same thing applies to code chunks with the chunk option error = FALSE.

Beyond the types of errors mentioned above, it may be tricky to find the source of the problem. For example, when you unintentionally unlink() the current directory, it should not stop the knitting process, because unlink() succeeded anyway. You may run into problems after the knitting process, e.g., LaTeX/HTML cannot find the output figure files. In this case, you can try to apply knit_exit() to all code chunks in the document one by one. One way to achieve this is to set up a chunk hook to run knit_exit() after a certain chunk. Below is an example of using linear search (you can improve it by using bisection instead):

#' Render an input document chunk by chunk until an error occurs
#'
#' @param input the input filename (an Rmd file in this example)
#' @param compile a function to compile the input file, e.g. knitr::knit, or
#' rmarkdown::render
knit_debug = function(input, compile = knitr::knit) {
library(knitr)
lines = readLines(input)
chunk = grep(all_patterns$md$chunk.begin, lines) # line number of chunk headers

knit_hooks$set(debug = function(before) {
if (!before) {
chunk_current <<- chunk_current + 1
if (chunk_current >= chunk_num) knit_exit()
}
})

opts_chunk$set(debug = TRUE)

# try to exit after the i-th chunk and see which chunk introduced the error
for (chunk_num in seq_along(chunk)) {
chunk_current = 0 # a chunk counter, incremented after each chunk
res = try(compile(input))
if (inherits(res, 'try-error')) {
message('The first error came from line ', chunk[chunk_num])
break
}
}
}

  1. This is by design. I think it is a good idea to have error = TRUE for code chunks, since sometimes we want to show errors, for example, for teaching purposes. However, if I allow errors for inline code as well, authors may fail to recognize fatal errors in the inline code. Inline code is normally used to embed values inline, and I don't think it makes much sense if an inline value is an error. Imagine a sentence in a report like The P-value of my test is ERROR, and if knitr didn't signal the error, it will require the authors to read the report output very carefully to spot this issue. I think it is a bad idea to have to rely on human eyes to find such mistakes.

Instruct R Markdown to ignore the rest of content from a specific point

In Rmarkdown, you have a code chunck as

```{r [options]}
your code
```

For options you have eval,echo,messages, etc., but the beauty is that they are passed as render works though it. So you should be able to do something akin to:

```{r setup,echo=FALSE}
run this
```

I am doing code stuff! *Yeah*

```{r load_data}
More code
evalfromhere=FALSE
```

```{r step2b,eval=evalfromhere}
Doesn't work yet
```

```{r name2,eval=evalfromhere}
Also not yet
```

Once you are satisfied, set evalfromhere to TRUE, or remove the chunk options as you go along.

Rmarkdown is based on knitr, so read these documentations: https://yihui.name/knitr/options/

trouble finding file source in .rmd chunk when knitting .rmd from master .R file

@Yihui: Perhaps you can make ../ an absolute path using normalizePath('../'). A relative working directory can be confusing to reason about (at least my head hurts after I read too many levels of relative paths :). BTW, when you Knit HTML in RStudio, RStudio first changes the working directory to the input Rmd file.

Me: yes! using just opts_knit$set(root.dir=normalizePath('../')) works for knitting the .rmd file from master.R and knitting to html or running all chunks from within the .rmd. I updated the github example. test-b.rmd now shows this. thanks!

Error with knitr when knitting Rmd to PDF, but code runs fine?

Your problem here is reproducibility and undefined variables. Much of your code in your question is not within a code chunk, so it will print (albeit not as code) but will not create variables, load libraries, etc. With that in mind, you may realize then that demo and cqb are never defined within the document.

That means that if either exists as an object in the base R environment, then they exist but are not what you think they are. In this case, demo is in fact a function utils::demo and is available, so merge tries to do something with it. Unfortunately, as you might expect, there is no logic to be able to do merge-like operations on a function.

I can reproduce you error on my console:

ls()
# character(0)

# 'demo' not defined as a frame, so still utils::demo
# 'cbq' does not matter, because 'merge' cannot get past the problem with 'demo'

merge(demo, cbq)
# Error in as.data.frame.default(x) :
# cannot coerce class '"function"' to a data.frame

The fix might be to put your initial code within a code block.

I don't know what you intend to do with the URLs in there, but here is a less malformed Rmd:

---
title: "[title]"
author: "[Name]"
output:
pdf_document: default
word_document:
fig_caption: yes
---

The code book of the two data sets can be found in these two links:

- wwwn.cdc.gov/Nchs/Nhanes/2015-2016/DEMO_I.htm
- wwwn.cdc.gov/Nchs/Nhanes/2015-2016/CBQ_I.htm

```{r}
library(knitr)
library(png)
install.packages("Hmisc")
library(Hmisc)
demo <- sasxport.get("https://wwwn.cdc.gov/Nchs/Nhanes/2015-2016/DEMO_I.XPT")
cbq <- sasxport.get("https://wwwn.cdc.gov/Nchs/Nhanes/2015-2016/CBQ_I.XPT")
```

`str(demo)`

`str(cbq)`

```{r}
eat <- merge(demo, cbq, by="seqn")
```

```{r}
dim(eat)
# = 52 columns
# = 9,971 rows

# OR can use
ncol(eat)
nrow(eat)
```

Some notes about this:

  • Unless this is intended to always run in a sterile R environment (e.g., docker container), then I find install.packages to be not only poor design but also not fair to anybody else that might use this Rmd document: perhaps I'm intending to stay on a stable older package version (reproducibility!), but just by rendering your document, my package is revocably upgraded.

  • You `str(demo)` is printing the literal string "str(demo)" in fixed-width font, but running nothing. This might either go in a code chunk, or you can use inline-code by using `r str(demo)` (that's backtick, "r", space, code, backtick).

RMarkdown code evaluation until command

From the documentation of knit_exit():

Sometimes we may want to exit the knitting process early, and completely ignore the rest of the document. This function provides a mechanism to terminate knit().

Example:

Text.

```{r}
print(1)
```

More text.

```{r}
knitr::knit_exit()
```

Ignored.

```{r}
print("Ignored.")
```

Everything after knit_exit() will be ignored. This works for all output formats.

The code above produces:

Sample Image



Related Topics



Leave a reply



Submit