utf8 in plot labels using knitr - r

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.

Related

Removing the space between a plot generated by R and the caption in an Rtex file

I am trying to edit an Rtex file and I'm creating plots. I have a plot below, which does compile. However, there is an empty white space below the caption. I can't figure out how to remove it. I have tried to search for solutions but to no avail:
https://support.sisense.com/kb/en/article/remove-whitespace-margins-from-plotly-charts - Relevant but for plotly. Was not
able to adapt it to my R code.
http://ostack.cn/qa/?qa=829717/ - Involved Python rather than R. I
could not adapt the solution into the R plot.
https://tex.stackexchange.com/questions/273786/latex-files-generated-by-tikzdevice-leaves-large-space-between-image-and-caption - Involved tikzpicture instead of R. I could not adapt the solution to the R plot.
The code which I'm running as well as the output is shown below. I am grateful if someone can help me. I have also tried the trimmws() function but it gave the following error:
## "Error in mysub(paste0("^", whitespace, "+"), x): argument"x" is missing, with no default."
\documentclass[a4paper,11pt]{article}
%Packages
\usepackage[justification=centering]{caption}
\usepackage{blindtext}
\begin{document}
\title{F-distribution}
\maketitle
\section{Diagram showing the $F$-distribution for a selected pair of values of the degree of freedom}
\blindtext
\begin{figure}[h!]
<<echo=FALSE, cache=TRUE, fig.width=5, fig.height=5>>=
curve(df(x, df1=20, df2=20))
#
\caption{Hi}
\end{figure}
\blindtext
\blindtext
\end{document}
Your image does have quite a lot of white space around it. You can move the caption further up with this quick hack:
\documentclass[a4paper,11pt]{article}
%Packages
\usepackage[justification=centering]{caption}
\usepackage{blindtext}
\begin{document}
\title{F-distribution}
\maketitle
\section{Diagram showing the $F$-distribution for a selected pair of values of the degree of freedom}
\blindtext
\begin{figure}[h!]
<<echo=FALSE, cache=TRUE, fig.width=5, fig.height=5>>=
curve(df(x, df1=20, df2=20))
#
\vskip-1cm
\caption{Hi}
\end{figure}
\blindtext
\blindtext
\end{document}

Show only selected figures of generated figures in a cache in knitr

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}

Displaying <<..>>= in output

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.

Getting Sweave code chunks to stay inside page margins?

Sometimes I get to make an R code chunk (in Sweave) which is longer then the margins of the page. Is there a way to force it to "go to the next line" once that happens?
Here is a simple example of that happening:
\documentclass[a4paper]{article}
\usepackage{Sweave}
\DefineVerbatimEnvironment{Sinput}{Verbatim} {xleftmargin=2em,
frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{xleftmargin=2em,
frame=single}
\title{Sweave with boxes}
\begin{document}
\maketitle
<<echo=FALSE>>=
options(width=60)
#
Here is an example of a code chunk followed by an output chunk,
both enclosed in boxes.
<<>>=
print(rnorm(99))
#
<<>>=
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
#
\end{document}
This is a difficult and extreme case, because you do not have spaces among those a's, so LaTeX may not be able to wrap the words. If you do have spaces, knitr will be able to produce the output with the long lines wrapped with tidy=TRUE, highlight=TRUE (so will Sweave, I think, if you set keep.source=FALSE).

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