问题
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?
回答1:
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 ...)

回答2:
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}
来源:https://stackoverflow.com/questions/19715551/knitr-changing-my-reverse-assignment-operator-to