I would like to know how to display the result of a variable that is in the environment
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
Hello,
\input{test2.Rnw}
\end{document}
test2.Rnw
\section{test}
<<eval=TRUE, echo=F>>=
paste0("my variable v is worth: ", v)
#
When I compile I get this
You can use the knitr package inside your Rmarkdown code. Check https://riptutorial.com/r/topic/4334/r-in-latex-with-knitr and also this SO Q&A : knitr chunk option eval=TRUE, echo=TRUE, include=FALSE
Related
I have the below combined systems for writing report with Knitr and LaTeX,
Rstudio Version 0.99.473 with R version 3.2.2
Knitr_1.11
MiKTeX 2.9
Windows 7
An example .Rnw code is shown below, my issue is that a text string "latticeknitrstatsgraphicsgrDevicesutilsdatasetsmethodsbase" was created right underneath "Figure 1: Test". I wonder how to get rid of it.
\documentclass[letterpaper]{article}
\title{An example}
\author{Me}
\date{\today{}}
<<setup, include=FALSE, cache=FALSE>>=
knit_hooks$set(myPackage = function(before, options, envir){
if(before)
library(lattice) else NULL
})
#
\begin{document}
\maketitle
\newpage
\section{My section 1}
\begin{figure}
\caption{Test}\label{fig:GofBase}
<<myPackage=TRUE, echo=FALSE, results='asis', cache=TRUE, fig.show='hold', fig.align='center', warning=FALSE>>=
xyplot(rnorm(100)~rnorm(100))
#
\end{figure}
\end{document}
As the question is not very clearly formulated, and the minimal example is not absolutely "minimal", here a improved version:
Question
Why does the following minimal example add a string like latticeknitrstatsgraphicsgrDevicesutilsdatasetsmethodsbase to the output?
\documentclass{article}
<<setup>>=
knit_hooks$set(myPackage = function(before, options, envir){
if(before) library(lattice)
})
#
\begin{document}
<<myPackage=TRUE>>=
xyplot(rnorm(100)~rnorm(100))
#
\end{document}
Answer
This has nothing to do with lattice and it's not a special feature of knitr chunk hooks.
What happens?
When a chunk hook returns a character value, this value is included in the output:
In knitr, hooks can also be used to insert texts into the output. To do this, the hook function must return a character result. [knitr: hooks]
In this case, there is no explicit return value of the hook. Therefore, the return value of if() is returned. if() in turn returns the value that library returns:
if returns the value of the expression evaluated, or NULL invisibly if none was (which may happen if there is no else). [see ?"if"]
And finally:
library returns (invisibly) the list of attached packages [see ?libray]
How to avoid it?
First of all, the example is not very good. There's no reason to load a package using a chunk hook. If lattice is required, it should be loaded in the setup chunk.
But there may be cases where a similar chunk hook is useful. Then, the solution is to explicitly return NULL:
knit_hooks$set(myPackage = function(before, options, envir){
if(before) library(lattice)
return(NULL)
})
Here is a minimally changed version that "works for me" (also from RStudio)
\documentclass[letterpaper]{article}
\title{An example}
\author{Me}
\date{\today{}}
<<setup, include=FALSE, cache=FALSE, echo=FALSE>>=
knit_hooks$set(myPackage = function(before, options, envir){
if(before)
library(lattice) else NULL
})
#
\begin{document}
%\SweaveOpts{concordance=TRUE}
\maketitle
\newpage
\section{My section 1}
\begin{figure}
\caption{Test}\label{fig:GofBase}
<<myPackage=TRUE, echo=FALSE, cache=FALSE, fig.show='hold', fig.align='center', warning=FALSE>>=
print(xyplot(rnorm(100)~rnorm(100)))
#
\end{figure}
\end{document}
I added a echo=FALSE to the first chunk, and removed results='asis' from the second chunk.
I'm using Sweave to make a report in R-Studio, and I have the problem, that my teacher will only accept reports, where the code is placed in an Appendix. This means that I need to control the position of the chunk outputs (graphs).
Is this possible in Sweave?
Regards,
Jens
This will return everything in your code. Using the \usepackage{fancyvrb} and the \VerbatimInput{test.Rnw} assuming that your file is named test.Rnw
\documentclass{article}
\usepackage{fancyvrb}
\begin{document}
\SweaveOpts{concordance=TRUE}
<<my_code_chunk>>=
2+2
#
\section{Appendix}
\VerbatimInput{test.Rnw}
\end{document}
Here is another example
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
<<my_code_chunk>>=
2+2
#
\section{Appendix}
<<>>=
<<my_code_chunk>>
#
\end{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.
If I have a chunk that generates 4 figures and I want to keep them all (fig.keep=all), is it possible to show only the second one using a cache option? I see that echo=2:5 can be selected, but it doesn't seem that fig.show=2 is possible. Is the best method to do \includegraphcis{fig2.pdf}?
Thanks.
If you don't want to keep all figures you can simply use :
Use argument fig.keep=c(2,4)
Reproducible example :
\documentclass[a4paper]{article}
\begin{document}
<<load_libraries, echo = FALSE, eval = TRUE, results ="hide">>=
library(knitr)
#
<<multiplefig, fig.keep=c(2,4),fig.height=4,fig.with=10, out.width='.8\\linewidth'>>=
mapply(function(X)plot(X,main=X),c(1:4))
#
\end{document}
However, since you want to keep figures, I would do it the old way in sweave, save the figures using png or pdf.
Reproducible example :
\documentclass[a4paper]{article}
\usepackage{graphicx}
\graphicspath{{figure/}}
\begin{document}
<<multiplefig, echo=FALSE>>=
for (i in 1:4){
png(file=paste0(getwd(),"/figure/fig",i,".png"))
plot(1,1,main=i,cex.main=4)
dev.off()
}
#
This plot shows only figure \ref{fig:fig2} but 4 other are saved
\begin{figure}[htbp]
\centering
\includegraphics[width=0.5\textwidth]{fig2.png}
\caption{}
\label{fig:fig2}
\end{figure}
\end{document}
I want demonstrate a sample piece of R code WITH the knitr <<..>>= preamble in a LaTeX document. Here is an example of the output I desire:
It's got to be simple - but I'm missing something. I checked the documentation and scanned stack overflow - but without luck. Here is a MWE:
\documentclass{article}
\begin{document}
<<mychunk, cache=TRUE, eval=FALSE, dpi=100>>=
"hello world"
#
\end{document}
Suggestions? I tried indenting the code in LaTex and wrapping in a verbatim block, but only got errors.
I just checked the manual of knitr. This is how the package author solved the problem:
<<use-ext-chunk, echo=FALSE, comment=NA>>=
cat('<<Q1, echo=TRUE, tidy=TRUE>>=','#',sep='\n')
#
which produces the output as shown on page 9 of the knitr manual
Here is a minimal example:
\documentclass[a4paper]{article}
\begin{document}
<<use-ext-chunk, echo=FALSE, comment=NA>>=
cat('<<Q1, echo=TRUE, tidy=TRUE>>=','#',sep='\n')
#
\end{document}
which produces the attached output.
I had the same question on tex.stackexchange.com a year ago and got a few nice responses: https://tex.stackexchange.com/q/35485/3419. This is for Sweave but I think it will work the same in knitr.
I think I ended up just using \Sexpr{"<<>>="} and \Sexpr{"#"} in verbatim environment. e.g.:
\documentclass{article}
\begin{document}
\begin{verbatim}
\Sexpr{"<<mychunk, cache=TRUE, eval=FALSE, dpi=100>>="}
"hello world"
\Sexpr{"#"}
\end{verbatim}
\end{document}
Just a quick follow-up: this feature has been implemented in knitr (devel version >= 0.8.15); see examples for both Rnw and Rmd. An alternative solution is in knitr FAQ.