3
votes

I wonder how to suppress error messages in knitr. My MWE is below:

\documentclass{article} 
\begin{document}
<< Test >>=
1:10
X
@ 
\end{document}

Edited

The object X does not exist. I want to show X in my code chunk and want to evaluate it too even this will throw an error. But doesn't want to show any errors in my .tex document same as we can suppress warnings by setting warning=FALSE.

1
Yes X does not exist and will produce error. I don't want to show any error message in my knitr file.MYaseen208
Yes I want to show X in my code chunk and want to evaluate it too. But doesn't want to show any errors as we can suppress warnings by setting warning=FALSE.MYaseen208
Try error=FALSE, but your goal is not fully clear for me.DrDom
OP just wants to have the code run, without showing the errors, how is this unclear?Roman Luštrik
It would appear include chunk option fails when there is an error in the chunk. I hope @Yihui will chime in if it's possible to stop the chunk from appearing in the result no matter what.Roman Luštrik

1 Answers

6
votes

Errors have their own dedicated hook function, stored in the environment accessed by knit_hooks$get(). Here, for your enlightenment, is the complete list of those functions:

names(knit_hooks$get())
# [1] "source"   "output"   "warning"  "message"  "error"    "plot"    
# [7] "inline"   "chunk"    "document"

To suppress warnings, just overwrite the default error hook function with one that takes the required arguments, but doesn't return anything at all.

\documentclass{article}
\begin{document}

<<setup, include=FALSE, cache=FALSE>>=
muffleError <- function(x,options) {}
knit_hooks$set(error=muffleError)
@

<<Test>>=
1:10
X
@
\end{document}

Which, upon compilation, yields the following

enter image description here