How to format output of results using output hooks in knitr? - r

I have a Rnw file a.Rnw with the following contents:
\documentclass{beamer}
\begin{document}
\begin{frame}[fragile]
<<>>=
1+1
#
\end{frame}
\end{document}
I produce a pdf by
Rscript -e 'knitr::knit("a.Rnw")'
pdflatex a.tex
The output in a.pdf looks like this:
How do I get the output to look like this:
R> 1+1
## [1] 2
That is, how do I put R> in front of the R code and remove the blank line between code and output?

To show R> in front of all R commands, I set the R prompt using options and tell knitr to show the prompt using opts_chunk (code at bottom of answer).
Getting rid of the new line is a bit trickier because the R code and R output in the generated tex file looks like this:
\begin{alltt}
\hlstd{R> }\hlnum{1}\hlopt{+}\hlnum{1}
\end{alltt}
\begin{verbatim}
## [1] 2
\end{verbatim}
So the newline between R code and its output is not generated explicitly by knitr, but is due to a new paragraph being started between \end{alltt} and \begin{verbatim}. The verbatim environment adds above and below it the current value of \topsep (see here). So I patch the knitrout environment such that this variable is locally set to 0pt. Here is the new version of a.Rnw:
\documentclass{beamer}
% reduce whitespace between R code and R output
\let\oldknitrout\knitrout
\renewenvironment{knitrout}{
\begin{oldknitrout}
\topsep=0pt
}{
\end{oldknitrout}
}
% show R> prompt before R commands
<<r setup, echo=FALSE>>=
options(prompt='R> ')
knitr::opts_chunk$set(prompt=TRUE)
#
\begin{document}
\begin{frame}[fragile]
<<>>=
1+1
#
\end{frame}
\end{document}
and the output looks like this:

Related

Chunk output without knitrout and verbatim environment

<<newChunk,echo=FALSE,comment=NA,background=NA>>=
x <- "\\includegraphics[width=\\maxwidth]{figure/Kompetenz1.pdf}"
cat(x)
#
If I run this r code in my .Rnw file I will get the following output in my .tex file:
\begin{knitrout}
\definecolor{shadecolor}{rgb}{1, 1, 1}\color{fgcolor}\begin{kframe}
\begin{verbatim}
\includegraphics[width=\maxwidth]{figure/Kompetenz1.pdf}
\end{verbatim}
\end{kframe}
\end{knitrout}
How can I get just the \includegraphics{...} without any environment in my .tex file?
I am not sure why you are using Knitr in the first place. It looks like your just trying to include a PDF in your latex document. To do that I would use the command:
\includepdf[pages=-]{figure/Kompetenz1.pdf}
or
\includegraphics[width=\maxwidth]{figure/Kompetenz1.pdf}
In your Rnw file. No need for a Knitr chunk here.
The answer from #baptiste was right.
Why I was using a Knitr chunk was to loop over some values. Here is my example code:
<<Ueberblick, echo = FALSE, results = 'asis'>>=
for(i in 1:nrow(Kompetenzen)){
cat(paste("\\includegraphics[width=\\maxwidth]figure/Kompetenz.pdf}",i," \\newline ",sep=""))
}
#
Thanks for the help!

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.

How to write an if-then statement in LaTeX using the value of an R variable in knitr/Sweave

I am currently using knitr along with R 3.0.2 and RStudio in order to produce a LaTeX report. My report is typed up as a .Rnw file, and compiled using the knit2pdf function.
I would like to use an if-then formulation in LaTeX in order to create a separate section, but have the if-then condition use the value of a variable from R (let's call it CreateOptionalSection).
Is this possible? If so, how can I refer to the R variable in the .tex document?
Add \usepackage{comment} to the preamble of your latex file.
At the line before the optional section starts, do
<<startcomment, results='asis', echo=FALSE>>=
if(!CreateOptionalSection){
cat("\\begin{comment}")
}
#
At the line after the optional section ends, do
<<endcomment, results='asis', echo=FALSE>>=
if(!CreateOptionalSection){
cat("\\end{comment}")
}
#
You can do it directly in R code in your .Rnw file, using cat to paste the section. Here is an example, when x > 0 it creates section 1, when x < 0 it creates section 2:
\documentclass{article}
\begin{document}
<<condition, include=FALSE, echo=FALSE>>=
x<- rnorm(1)
if(x>0){
text <- "\\section{Section 1}
This is new section 1"
}else{
text <- "\\section{Section 2}
This is new section 2"
}
#
Testing the code: the result of x (which here was \Sexpr{x}) will determine the section.
<<print, results='asis', echo=FALSE>>=
cat(text)
#
\end{document}
This will give you:

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