Suppressing Error Messages in knitr - r

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.

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

Related

why suppress Error in Rmarkdown doesn't work?

I want to supress Errors in Rmw files. So, i've tried to set the global chunk option error=TRUE, but it doesn't work. Also it doesn't work to set the chunk option error=TRUE directly in the chunk.
Here is an example code:
\begin{document}
\SweaveOpts{concordance=TRUE}
abc
<<setup, cache=F, include=F>>=
library(knitr)
library(formatR)
opts_chunk$set(error=TRUE)
knit_hooks$set(error=TRUE)
#
<<a,error=TRUE>>=
A <- 5
# of course, that doesnt work, but i want the error message as chunk output
A * B
#
\end{document}
I don't understand why it doesn't work
Only the error message:
"Error in eval(expr, .GlobalEnv) : object 'L' not found"
appears.
You seem to be using Sweave from base R rather than knitr. If you were using knitr, you'd get a warning about the \SweaveOpts{concordance=TRUE} statement.
If you are using RStudio, this is one of the Project Options. If you are running things directly, run knitr::knit("<your filename>"), instead of Sweave("<your filename>").
There are a couple of other errors that will stop knitr from working; this version fixes them:
\documentclass{article}
\begin{document}
abc
<<setup, cache=F, include=F>>=
library(knitr)
library(formatR)
opts_chunk$set(error=TRUE)
#
<<a,error=TRUE>>=
A <- 5
# of course, that doesnt work, but i want the error message as chunk output
A * B
#
\end{document}
The changes were:
You need the \documentclass line at the start.
You don't want the \SweaveOpts{concordance=TRUE} statement.
You don't want the knit_hooks$set(error=TRUE) statement.

knitr: Modifying plot hook -- inconsistent

I am trying to modify plot hook. However, the behaviour is for some reason dependent on whether I make this modification in compiled file or before that. I would like to do it before that (more files).
Minimal example:
```{r test}
print("this is test")
plot(1:10)
```
With this hook modification:
```{r setting, echo=FALSE}
plot_hook = knit_hooks$get("plot")
new_plot_hook = function(x, options){
x = paste0("{random-change}", x)
plot_hook(x, options)
}
knit_hooks$set(plot=new_plot_hook)
```
If set in file, before code-chunk, it compiles into:
```r
print("this is test")
```
```
## [1] "this is test"
```
```r
plot(1:10)
```
![plot of chunk test]({random-change}figure/test-1.png)
However, when I do modification before running knit, I get:
print("this is test")## [1] "this is test"
plot(1:10){random-change}figure/test-1.pdf
Why? What is going wrong? Why knitr won't let me modify hook before file compilation? How to solve it?
edit: I probably found an answer:
Trying to set Knitr 'document' output hook results in code chunk line breaks being lost
So I first need to call render_markdown() to load markdown chunk setting, which notably changes code in knit_hooks$get("plot"). Then I can run my code and knit my Rmakrdown with required output.
However, I know how, but I still don't know why. Yihui in linked answer mentions, that hooks should be set only inside file. My theory is that while calling knit, knitr detects file type and thus required pattern type and set hooks for that specific format. But not if I change it prior to calling knit.

Passing values from an Rnw file to an R script

Since I am a newbie as far as knitr is concerned, I am reading and modifying the examples given in knitr web site. One the approaches that caught my attention is to call chunks of an R script within an Rmw file. After compiling and modifying several examples, I wonder whether one can set a variable on an Rmw file and pass it to an R-script.
Here is an example
\documentclass{article}
\begin{document}
<<set-options, echo=FALSE, cache=FALSE>>=
options(replace.assign=TRUE)
opts_chunk$set(cache=TRUE, fig.show='asis')
read_chunk('simple_example.R')
#
\title{Example}
\author{Somebody}
\maketitle
\section{Print variable}
<<Print-data, echo=TRUE>>=
inp=2
#
\end{document}
and
# Simple Example
## ---- Print-data ----
inp=inp+2
print(inp)
The output result is ip=2 and an error msg "object inp not found".
Many thanks
The code chunk Print-data overrode the one in the Rnw file, so inp=2 was not executed, hence the error.
It seem you want to embed the chunk after Print-data:
<<>>=
inp=2
<<Print-data>>
#

Display the knitr code chunk source in document

I'm trying to output the source of a knitr chunk onto a beamer slide.
For example, I would like the following code chunk to be displayed as is in the .Rnw:
<<code-chunk, echo=TRUE, tidy=TRUE>>=
#
I've attempted to recreate this behavior using:
<<out-first-code-chunk, echo=FALSE, comment=NA>>=
cat(paste("<<example-code-chunk, echo=TRUE, tidy=TRUE>>=","#",sep="\n"))
#
This code is legitimate since the cat command in R's console gives:
> cat('<<example-code-chunk, echo=TRUE, tidy=TRUE>>=','#',sep='\n')
<<code-chunk, echo=TRUE, tidy=TRUE>>=
#
However, the resulting latex:
\begin{frame}
\frametitle{Code Chunk}
To incorporate R code into your knitr documents
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{verbatim}
<<example-code-chunk, echo=TRUE, tidy=TRUE>>=
#
\end{verbatim}
\end{kframe}
\end{knitrout}
Throws errors:
<<example-code-chunk, echo=TRUE, tidy=TRUE>>= # \end {verbatim} \end
\ETC. ! Paragraph ended before \#xverbatim was complete. <to be read
again> \par l.198 \end{frame} I suspect you've forgotten a `}',
causing me to apply this control sequence to too much text. How can we
recover? My plan is to forget the whole thing and hope for the best. !
LaTeX Error: \begin{verbatim} on input line 198 ended by
\end{beamer#framepau ses}. See the LaTeX manual or LaTeX Companion for
explanation. Type H <return> for immediate help. ... l.198 \end{frame}
Your command was ignored. Type I <command> <return> to replace it with
another command, or <return> to continue without it. ! LaTeX Error:
\begin{kframe} on input line 198 ended by \end{beamer#frameslide }.
Why is the latex environment thinking that verbatim was not closed? Is there a more appropriate way to display a code-chunk in its entirety?
This should do it...
1 line in the setup chunk, and 1 extra param in the chunk desired for output...
Console:
`install.packages(devtools)`
`devtools::install_github("thell/knitliteral")`
For .Rnw:
<<"knitr-setup", include=FALSE, cache=FALSE>>=
knitLiteral::kast_on()
#
<<"my_chunk", eval=FALSE, opts.label="literal-literal">>=
# Something that will not be output in the doc.
#
Output:
<<"my_chunk", eval=FALSE>>=
#
For .Rmd:
````{r knitr_setup, include=FALSE, cache=FALSE}
knitLiteral::kast_on()
````
````{r my_chunk, opts.label="literal-literal"}
# Something that will not be output in the doc.
````
Output:
````{r my_chunk}
````
** The use of 4 backticks keeps syntax highlighting as valid R (where used).
From this chunk and what you can see in the source of the example Literal Markdown doc and the rendered doc that there is no need to have a complex chunk.
The sweave example file is also available showing the same examples.

Knitr inline chunk options (no evaluation) or just render highlighted code

I cannot find information on whether it is possible to specify options for inline chunks in knitr. I've just tried specifying them, as in the regular chunk, but this gives an error.
What I need is to include R code with highlighting in a PDF, but without evaluating it. This can only happen with inline chunks due to the format of the context. Or perhaps there is another way to include highlighted code.
To provide an example, I need something in the lines of:
Some text about something with `r eval=FALSE 1+1` inside the sentence.
This particular syntax gives:
Error in parse(text = code, keep.source = FALSE) :
<text>:1:11: unexpected ','
1: eval=FALSE,
Thanks to Yihui you can do,
\documentclass{article}
<<setup, include=FALSE>>=
knit_hooks$set(inline = function(x) {
if (is.numeric(x)) return(knitr:::format_sci(x, 'latex'))
highr::hi_latex(x)
})
#
\begin{document}
the value of $\pi$ is \Sexpr{pi}, and the function to read a table is
\Sexpr{'read.table()'}.
<<test2>>=
rnorm(10)
#
\end{document}

Resources