I am having trouble when using "reverse" assignment operators (->) in a knitr .Rnw file. For example, I have the following simple .Rnw file
\documentclass{article}
\begin{document}
<<test>>=
options(tidy=FALSE, width=50)
1:5 -> a
#
\end{document}
When I use knitr to compile into a pdf, the operator -> has been reversed so the output actually has
1:5 <- a
in it!
how can I change this?
Make tidy=FALSE a knitr chunk option rather than an R option:
\documentclass{article}
\begin{document}
<<test,tidy=FALSE>>=
options(tidy=FALSE, width=50)
1:5 -> a
#
\end{document}
(I don't think tidy=FALSE does anything at all in options(), but I guess it's harmless ...)
For setting tidy=FALSE on a chunk-by-chunk basis, Ben's answer has got you covered.
To reset the option globally, use opts_chunk$set(), like so:
\documentclass{article}
\begin{document}
<<setup, include=FALSE, cache=FALSE>>=
opts_chunk$set(tidy=FALSE)
#
<<test>>=
1:5 -> a
#
\end{document}
Additionally, as documented here, tidy.opts can give you finer-grained control over many aspects of the knitr's (and ultimately formatR::tidy.source()'s) tidying behavior. Perhaps unfortunately in this case, while you can tell knitr not to replace "=" with "<-" (by doing opts_chunk$set(tidy.opts=list(replace.assign=FALSE))you cannot use that option to control whether "->" is replaced by "<-".
Here's an example that uses tidy.opts
\documentclass{article}
\begin{document}
<<setup, include=FALSE, cache=FALSE>>=
opts_chunk$set(tidy.opts=list(replace.assign=FALSE))
#
<<test>>=
j <- function(x) { x<-y ## x<-y will be printed on new line, with added inter-token spaces
a = 1:5 ## will be indented, but "=" won't be replaced
} ## closing brace will be moved to start of line
#
\end{document}
Related
My question is the same as the one in the link Sweave syntax highlighting in output.
I have followed the suggestion by daroczig https://tex.stackexchange.com/questions/5113/how-to-colorize-syntax-using-r-sweave, and created the following test.Rnw file:
\documentclass{article}
\RequirePackage{fancyvrb}
\RequirePackage{listings}
\SweaveOpts{keep.source=TRUE}
<<SweaveListingsPreparations, results=tex, echo=FALSE, strip.white=false>>=
require(SweaveListingUtils)
SweaveListingPreparations()
setToBeDefinedPkgs(pkgs = c("SweaveListingUtils","distr"),
keywordstyles = c("\\bf\\color{blue}","\\bf\\color{red}"))
#
\begin{document}
\SweaveOpts{concordance=TRUE}
\section{Example}
This is an example with three variables in R.
<<>>=
options(continue = " ")
x <- 10
t <- 'The brown fox'
b <- TRUE
#
<<>>=
x
#
<<>>=
t
#
<<>>=
b
#
\end{document}
<<cleaup, echo=FALSE>>=
unloadNamespace("SweaveListingUtils")
#
However, I get the following error message:
Suggestions?
Since you don't have \usepackage{Sweave} in your document, Sweave will insert it. But the SweaveListingsUtils package also inserts conflicting code.
So you need to follow the advice in the SweaveListingsUtils documentation, and put in a comment
% \usepackage{Sweave}
near the start of your document. This will prevent R from inserting it.
However, do note that support for SweaveListingsUtils is ending; you are better off using knitr.
I want to know if there is a way to print R object directly in a text (Sweave), but directly in a line of text.
I'd like to print this code
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
YO MANNNNNNN 2+2 =
<<here, results=tex, echo=FALSE>>=
2+2
#
YEAHHHH!
\end{document}
And I want an output similar to this:
YO MANNNNNNN 2+2 = 4 YEAHHHH!
But, R is adding the answer brackets like this
YO MANNNNNNN 2+2 = [1] 4YEAHHHH!
Code:
\documentclass{article}
\begin{document}
% \SweaveOpts{concordance=TRUE}
YO MANNNNNNN 2+2 = \Sexpr{2+2} YEAHHHH!
\end{document}
n.b. For me commenting out \SweaveOpts{concordance=TRUE} worked just fine, but you made need to uncomment depending on your setup.
Prints:
YO MANNNNNNN 2+2 = 4 YEAHHHH!
Update - extra info per comment...
You can define an object within a 'chunk' to be later evaluated in line using \Sexpr{}
<<somechunk, results='tex',echo=FALSE, results='hide'>>=
x <- 2
#
Inline evaluation of x prints the number \Sexpr{x}.
I am currently using knitr in R and RStudio to produce a LaTeX output. My code is a .Rnw file (called, say, testKnitr.Rnw) that is compiled to a pdf file with:
knit("testKnitr.Rnw") // in RStudio
pdflatex testKnitr.tex // in terminal
I would like to use an if-else syntax in LaTeX so that, depending on the value of an R variable, one of two LaTeX text paragraphs are output. In these LaTeX paragraphs, I would like to use expressions like \Sexpr{} and and \ref.
I have a minimal-working-example that is based on the second answer to a similar question posted here:
How to write an if-then statement in LaTeX using the value of an R variable in knitr/Sweave
Here is the MWE:
\documentclass{article}
\begin{document}
<<include=FALSE>>=
library(knitr)
opts_chunk$set(
concordance=TRUE
)
#
<<condition, include=FALSE, echo=FALSE>>=
x<- rnorm(1)
if(x>0){
text <- "This means x value of \Sexpr{x} was greater than 0"
}else{
text <- "This means x value of \Sexpr{x} was less than 0"
}
#
Testing the code:
<<print, results='asis', echo=FALSE>>=
cat(text)
#
\end{document}
Ideally, the intended output of the above MWE would a report with one line that contained something like:
"This means x value of 0.87 was greater than 0"
or
"This means x value of -0.87 was less than 0"
Before answering this question, I would like to take a look at the meta-question of whether this should be done.
Should we do it?
I don't think so. What we are basically doing here is using knitr to insert \Sexpr{x} in a document and then interpret \Sexpr{x}. There are no (obvious) reasons why we should take this detour instead of inserting the value of x directly to the document.
How to do it?
The following minimal example shows how it could be done anyways:
\documentclass{article}
\begin{document}
<<setup, echo = FALSE>>=
library(knitr)
knit_patterns$set(header.begin = NULL)
#
<<condition, echo=FALSE>>=
x <- rnorm(1)
if (x > 0) {
text <- "This means x value of \\Sexpr{x} was greater than 0"
} else {
text <- "This means x value of \\Sexpr{x} was less than 0"
}
#
Testing the code:
<<print, results='asis', echo=FALSE>>=
cat(text)
#
\end{document}
Two things are important here:
We need to escape the backslash in \Sexpr, resulting in \Sexpr.
We need to set knit_patterns$set(header.begin = NULL).
To compile the document:
Save it as doc.Rnw.
Then execute:
knitEnv <- new.env()
knit(input = "doc.Rnw", output = "intermediate.Rnw", envir = knitEnv)
knit2pdf(input = "intermediate.Rnw", output = "doc_final.tex", envir = knitEnv)
What happens?
The first call of knit generates intermediate.Rnw with the following content:
\documentclass{article}
\begin{document}
Testing the code:
This means x value of \Sexpr{x} was less than 0
\end{document}
You should note that knitr didn't include any definitions, commands etc. as usual to the LaTeX code. This is due to setting header.begin = NULL and documented here. We need this behavior because we want to knit the resulting document again in the second step and LaTeX doesn't like it when the same stuff is defined twice.
Creating the new environment knitEnv and setting it as envir is optional. If we skip this, the variable x will be created in the global environment.
In the second step we use knit2pdf to knit intermediate.Rnw and immediately generate a PDF afterwards. If envir was used in the first step, we need to use it here too. This is how x and it's value are conveyed from the first to the second knitting step.
This time all the gory LaTeX stuff is included and we get doc_final.tex with:
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin#nat#width>\linewidth
\linewidth
\else
\Gin#nat#width
\fi
}
\makeatother
%% more gory stuff %%
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Testing the code:
This means x value of \ensuremath{-0.294859} was less than 0
\end{document}
Here's an .Rnw MWE:
\documentclass{article}
<<setup, include=FALSE>>=
opts_chunk$set(cache=TRUE, eval=FALSE)
#
\begin{document}
Function highlighted:
<<c1>>=
print(iris)
#
Function highlighted if parameter is present:
<<c2>>=
library(magrittr)
iris %>%
print(someparam = 42)
#
No highlighting:
<<c3>>=
iris %>%
print
#
\end{document}
It renders like so:
How can I force syntax highlighting for the last print function?
The only suitable solution I found so far is to modify the latex source produced by knitr. Namely, changing \hlstd(print) (standard highlighting) to \hlkwd(print) (function highlighting + bold by default) manually should do the job.
I am having trouble when using "reverse" assignment operators (->) in a knitr .Rnw file. For example, I have the following simple .Rnw file
\documentclass{article}
\begin{document}
<<test>>=
options(tidy=FALSE, width=50)
1:5 -> a
#
\end{document}
When I use knitr to compile into a pdf, the operator -> has been reversed so the output actually has
1:5 <- a
in it!
how can I change this?
Make tidy=FALSE a knitr chunk option rather than an R option:
\documentclass{article}
\begin{document}
<<test,tidy=FALSE>>=
options(tidy=FALSE, width=50)
1:5 -> a
#
\end{document}
(I don't think tidy=FALSE does anything at all in options(), but I guess it's harmless ...)
For setting tidy=FALSE on a chunk-by-chunk basis, Ben's answer has got you covered.
To reset the option globally, use opts_chunk$set(), like so:
\documentclass{article}
\begin{document}
<<setup, include=FALSE, cache=FALSE>>=
opts_chunk$set(tidy=FALSE)
#
<<test>>=
1:5 -> a
#
\end{document}
Additionally, as documented here, tidy.opts can give you finer-grained control over many aspects of the knitr's (and ultimately formatR::tidy.source()'s) tidying behavior. Perhaps unfortunately in this case, while you can tell knitr not to replace "=" with "<-" (by doing opts_chunk$set(tidy.opts=list(replace.assign=FALSE))you cannot use that option to control whether "->" is replaced by "<-".
Here's an example that uses tidy.opts
\documentclass{article}
\begin{document}
<<setup, include=FALSE, cache=FALSE>>=
opts_chunk$set(tidy.opts=list(replace.assign=FALSE))
#
<<test>>=
j <- function(x) { x<-y ## x<-y will be printed on new line, with added inter-token spaces
a = 1:5 ## will be indented, but "=" won't be replaced
} ## closing brace will be moved to start of line
#
\end{document}