why suppress Error in Rmarkdown doesn't work? - r

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.

Related

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>>
#

Suppressing Error Messages in knitr

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

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.

utf8 in plot labels using knitr

Can't compile the following Rnw document into pdf using knitr
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}
\begin{document}
<<>>=
hist(rnorm(100),main="Гистограмма")
#
\end{document}
With labels in English everything is ok.
Edit 1:
Now i have two versions of pdf. In the first one letters are replaced by points.
In the second one all letters are overlapped. The second one is produced using addtional code chunk
<<>>=
pdf.options(encoding = "CP1251")
#
I am using Ubuntu 12.04 + R 2.14 + Texlive.
Edit 2:
For the moment i've found the following partial solution:
<<>>=
cairo_pdf("figure.pdf")
hist(rnorm(100),main="Гистограмма")
dev.off()
#
\includegraphics{figure.pdf}
Edit 3:
Using the following code:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}
\begin{document}
<<dev='cairo_pdf'>>=
hist(rnorm(100),main="Гистограмма")
#
\end{document}
I obtain a CORRECT histogram, with a lot of WARNINGS. How to avoid or at least suppress them?
Finally! Ura!
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}
\begin{document}
<<dev='cairo_pdf',warning=FALSE>>=
hist(rnorm(100),main="Гистограмма")
#
\end{document}
Could i avoid warnings? Can someone explain me all that stuff with encodings and warnings?
You may need to set pdf.options(encoding = 'your_encoding'); see https://github.com/yihui/knitr/issues/172 I'm not entirely sure what exactly the encoding should be here.

Is it possible to include a Sexpr before the expression has been evaluated in Sweave / R?

I'm writing a Sweave document, and I want to include a small section that details the R and package versions, platofrms and how long ti took to evalute the doucment, however, I want to put this in the middle of the document !
I was using a \Sexpr{elapsed} to do this (which didn't work), but thought if I put the code printing elapsed in a chunk that evaluates at the end, I could then include the chunk half way through, which also fails.
My document looks something like this
%
\documentclass[a4paper]{article}
\usepackage[OT1]{fontenc}
\usepackage{longtable}
\usepackage{geometry}
\usepackage{Sweave}
\geometry{left=1.25in, right=1.25in, top=1in, bottom=1in}
\begin{document}
<<label=start, echo=FALSE, include=FALSE>>=
startt<-proc.time()[3]
#
Text and Sweave Code in here
%
This document was created on \today, with \Sexpr{print(version$version.string)} running
on a \Sexpr{print(version$platform)} platform. It took approx sec to process.
<<>>=
<<elapsed>>
#
More text and Sweave code in here
<<label=bye, include=FALSE, echo=FALSE>>=
odbcCloseAll()
endt<-proc.time()[3]
elapsedtime<-as.numeric(endt-startt)
#
<<label=elapsed, include=FALSE, echo=FALSE>>=
print(elapsedtime)
#
\end{document}
But this doesn't seem to work (amazingly !)
Does anyone know how I could do this ?
Thanks
Paul.
This works just fine for me:
\documentclass{article}
\usepackage{Sweave}
\begin{document}
<<label=start, echo=FALSE, include=FALSE>>=
startt<-proc.time()[3]
#
Text and Sweave Code in here
This document was created on \today, with
\Sexpr{print(version$version.string)}.
<<results=hide,echo=FALSE>>=
Sys.sleep(2) # instead of real work
#
More text and Sweave code in here
<<label=bye, include=FALSE, echo=FALSE>>=
endt<-proc.time()[3]
elapsedtime<-as.numeric(endt-startt)
#
It took approx \Sexpr{elapsedtime} seconds to process.
\end{document}
I had to remove the version string inside the \Sexp{} as I get an underscore with via x86_64 which then upsets LaTeX. Otherwise just fine, and you now get the elapsed time of just over the slept amount.
You could use either R to cache the elapsed time in a temporary file for the next run, or pass it to LaTeX as some sort of variable -- but you will not be able to use 'forward references' as the R chunks gets evaluated in turn.
btw you don't usually need print to evaluate variables R
\Sexpr{version$version.string}
works fine as well
Dirk's answer is almost perfect, but still doesn't let you put the answer half way through the document. I got quite frustrated thinking it should work, but realised that the code I had was opening the time file at the start of each run (and emptying it) and writing the empty result into my document, then putting the answer in the time file at the end !
I eventually did something similar but using R to only open and write the file at the end, which worked great !;
\documentclass[a4paper]{article}
\usepackage[OT1]{fontenc}
\usepackage{longtable}
\usepackage{geometry}
\usepackage{Sweave}
\geometry{left=1.25in, right=1.25in, top=1in, bottom=1in}
\begin{document}
<<label=start, echo=FALSE, include=FALSE>>=
startt<-proc.time()[3]
#
Text and Sweave Code in here
%
This document was created on \today, with \Sexpr{print(version$version.string)} running
on a \Sexpr{print(version$platform)} platform. It took approx \input{time}
sec to process.
More text and Sweave code in here
<<label=bye, include=FALSE, echo=FALSE>>=
odbcCloseAll()
endt<-proc.time()[3]
elapsedtime<-as.numeric(endt-startt)
#
<<label=elapsed, include=FALSE, echo=FALSE>>=
fileConn<-file("time.tex", "wt")
writeLines(as.character(elapsedtime), fileConn)
close(fileConn)
#
\end{document}

Resources