Decreasing space between commands and output in knitr chunks - r

I'm using knitr with LaTeX and there seems to be a lot of space between the commands echoed by a code chunk and the start of the output:
The LaTeX code for this looks like:
\begin{knitrout}\scriptsize
\definecolor{shadecolor}{rgb}{1, 1, 1}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlstd{> }\hlstd{lda_test_pred} \hlkwb{<-} \hlkwd{predict}\hlstd{(lda_fit,} \hlkwc{newdata} \hlstd{= seg_test)}
\hlstd{> }\hlkwd{library}\hlstd{(pROC)}
\hlstd{> }
\hlstd{> }\hlstd{lda_roc} \hlkwb{<-} \hlkwd{roc}\hlstd{(}\hlkwc{response} \hlstd{= seg_test}\hlopt{$}\hlstd{Class,}
\hlstd{+ } \hlkwc{predictor} \hlstd{= lda_test_pred}\hlopt{$}\hlstd{posterior[,} \hlstr{"PS"}\hlstd{],}
\hlstd{+ } \hlcom{## we need to tell the function that the _first_ level}
\hlstd{+ } \hlcom{## is our event of interest}
\hlstd{+ } \hlkwc{levels} \hlstd{=} \hlkwd{rev}\hlstd{(}\hlkwd{levels}\hlstd{(seg_test}\hlopt{$}\hlstd{Class)))}
\hlstd{> }\hlstd{lda_roc}
\end{alltt}
\begin{verbatim}
Call:
roc.default(response = seg_test$Class, predictor = lda_test_pred$posterior[, "PS"], levels = rev(levels(seg_test$Class)))
Data: lda_test_pred$posterior[, "PS"] in 346 controls (seg_test$Class WS) < 664 cases (seg_test$Class PS).
Area under the curve: 0.874
\end{verbatim}
\begin{alltt}
\hlstd{> }\hlcom{# plot(exRoc print.thres = .5)}
\end{alltt}
\end{kframe}
\end{knitrout}
The space is generated between the end of alltt and the start of verbatim. Part of the gap, for this example, is the blank line prior to the call output.
Any ideas on how to modulate this in knitr (without affecting any spacing between paragraphs etc)?

Follow the advice found here
control vertical space before and after verbatim environment?
and add the following lines to your document:
\usepackage{etoolbox}
\makeatletter
\preto{\#verbatim}{\topsep=0pt \partopsep=0pt }
\makeatother
For some more detail you can check this answer.

Related

How to avoid "! LaTeX Error: Environment axis undefined" when using include_tikz with pgfplots?

I have successfully included in an R/exams .Rmd file several graphics made in TikZ. The same does not happen when I try to include a plot under pgfplots using include_tikz(). Whenever \begin {axis} and \end {axis} are included, beware of the error "! LaTeX Error: Environment axis undefined".
In the RStudio console the legend appears: "This is pdfTeX, Version 3.14159265-2.6-1.40.21 (TeX Live 2020) (preloaded format = pdflatex) restricted \ write18 enabled.entering extended mode", even having enabled in TexStudio write-18. None of these messages appear when I include other TikZ graphs other than pgfplots.
Any TikZ graph works when run in TexMaker or TexStudio, which indicates that it is not a problem of the absence of LaTeX libraries or packages.
I include a part of my code, adapted from https://www.latex4technics.com/?note=1HCT:
```{r datos1, echo = FALSE, results = "hide"}
library(exams)
typ <- match_exams_device()
image01<-'
\\begin{tikzpicture}
\\begin{axis}[legend pos=south east]
\\addlegendimage{empty legend}
\\addplot {sqrt(x)};
\\addplot {ln(x)};
\\addlegendentry{\\hspace{-.6cm}\\textbf{A title}}
\\addlegendentry{$\\sqrt{x}$}
\\addlegendentry{$\\ln{x}$}
\\end{axis}
\\end{tikzpicture}
'
```
```{r grafica01, echo = FALSE, results = "asis"}
include_tikz(image01, name = "grafiko1", markup =
"markdown",format = typ,library = c("arrows"),packages =
"booktabs",width = "7cm",header = "\\usepackage{/home/r-
exams/Documentos/NuevoRStudio/Rmarkdowns/
Esqueleto/exercises/schoice/
LaboratorioTikZ/3dplot}")
```
The answer is right there in your question title. You need to include the pgfplots package:
include_tikz(image01, packages = "pgfplots", ...)
The other packages, library, and header arguments from the call in your question are not needed.
The reason is that for include_tikz() you just use the {tikzpicture} code while in the full .tex file that you linked you additionally have:
\documentclass{standalone}
\usepackage{pgfplots}
\begin{document}
\begin{tikzpicture}
...
\end{tikzpicture}
\end{document}
Note the \usepackge{pgfplots} in the second line!

Blogdown fails rendering page as tikzmark library is not found

I am using latest version of blogdown and tinytex to render a page containing this snippet:
The following diagram:
```{r, echo=FALSE, engine='tikz', fig.cap='This is it.', engine.opts = list(template = "../latex/header.tex")}
\begin{tikzpicture}[scale=.7, remember picture]
\tikzmath{ \w = 6; \h =4; \x = 2; \y = 1; }
\draw [fill=gray!30,thick] (-\w/2,-\h/2) rectangle (\w/2,\h/2);
\draw [->,thick] (\w/2,0) -- (\w/2+\x,0);
\draw [->,thick] (-\w/2-\x,0) -- (-\w/2,0);
\node [left] at (-\w/2-\x,0) {Input};
\node [right] at (\w/2+\x,0) {Output};
\node [align=left,font=\ttfamily] at (0,0) {\small function(\subnode {sub}{...}) \{\\\hspace{0.2cm}...\\\}};
\draw[−>,thick] (-\w/2,0) -- (-\w/2 + \w/8,0) -- (-\w/2 + \w/8,\h/4) -- ($ (sub)+(-\w/2.5,\h/5) $) -- ($ (sub)+(0,\h/5) $) -- (sub);
\draw [->,thick] (0,0) -- (\w/2,0);
\end{tikzpicture}
```
Where header.tex is:
\documentclass{article}
\include{preview}
\usepackage[pdftex,active,tightpage]{preview}
\usepackage{amsmath}
\usepackage{tikz}
\usetikzlibrary{matrix}
% OWN CODE START
\usetikzlibrary{math}
\usetikzlibrary{tikzmark}
\usetikzlibrary{calc}
% OWN CODE END
\begin{document}
\begin{preview}
%% TIKZ_CODE %%
\end{preview}
\end{document}
When I run blogdown::build_site(), I get this error:
Quitting from lines 184-195 (mypost.Rmd)
Error: Failed to compile tikz1137adfc9b89.tex. See https://yihui.name/tinytex/r/#debugging for debugging tips. See tikz1137adfc9b89.log for more info.
Execution halted
Error in render_page(f) :
Failed to render 'content/mypost.Rmd'
file tikz1137adfc9b89.tex is (the last lines showing the error):
! Package tikz Error: I did not find the tikz library 'tikzmark'. I looked for
files named tikzlibrarytikzmark.code.tex and pgflibrarytikzmark.code.tex, but n
either could be found in the current texmf trees..
See the tikz package documentation for explanation.
Type H <return> for immediate help.
...
l.9 \usetikzlibrary{tikzmark}
Here is how much of TeX's memory you used:
12142 strings out of 494553
251420 string characters out of 6174236
281626 words of memory out of 5000000
15624 multiletter control sequences out of 15000+600000
3640 words of font info for 14 fonts, out of 8000000 for 9000
14 hyphenation exceptions out of 8191
55i,0n,68p,420b,90s stack positions out of 5000i,500n,10000p,200000b,80000s
! ==> Fatal error occurred, no output PDF file produced!
I am on Mac, on Windows this works :(
Installing the dev version fixes it:
devtools::install_github('yihui/tinytex')

knitr sanitize_fn warning incorporating plots into latex via knit2pdf

I am dynamically generating pdf reports in R using a driver script that calls knit2pdf. My report source is latex, in a .Rnw file, and the call is like this:
knit2pdf("source.Rnw",output=paste0(fname,".tex"),quiet=T)
fname does not contain any dots.
source.Rnw contains:
<<setup, echo=FALSE >>=
opts_chunk$set(fig.path=tempfile(tmpdir="work",pattern=fname,fileext=".pdf"))
#
<<custom-dev, echo=FALSE >>=
my_pdf<-function(file,width,height) {
pdf(file,width=5,height=2)
}
#
<<plot, echo=FALSE, results="asis", dev="my_pdf", fig.ext="pdf">>=
# A ggplot chart
print(g)
#
The reports are fine, but the following warning is generated from
knitr's sanitize_fn:
dots in figure paths replaced with _ ("work/fname_pdfplot")
Clearly, the offending . is coming from the fileext in opts_chunk. However, if I change that fileext to "_pdf", I don't get the plot in the report at all, and latex throws an error about the file (fname_pdfplot-1) not being found.
Ideas on how to (a) do this right so there's no warning, or (b) do this as I'm doing it but suppress this particular warning?
Edit 1:
Here is a working example of source.Rnw without using fileext. This does seem to be closer, because now it breaks with an error due to putting work\fname... in includegraphics rather than work/fname..., and if I change the backslash to a proper slash, it compiles cleanly.
tempfile is returning work\fname..., so perhaps my fix is just to re-escape those backslashes (or replace them with a forward slash). Is this something I should have known to do already?
\documentclass[titlepage]{article}
\usepackage[utf8]{inputenc}
\usepackage[headheight=36pt, foot=24pt, top=1in, bottom=1in, left=1in, right=1in, landscape]{geometry}
\usepackage{hyperref}
\usepackage{bookmark}
\usepackage{fancyhdr}
\usepackage{longtable}
\usepackage{multirow}
\usepackage{float}
\usepackage{booktabs}
\usepackage{tabularx}
\usepackage{microtype}
\usepackage{libertine}
\usepackage{parskip}
\usepackage{environ}
\usepackage{preview}
\usepackage[labelformat=empty]{caption}
\usepackage{amssymb}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\usepackage{picture}
\usepackage{needspace}
\usepackage{adjustbox}
\usepackage{graphicx}
\pagestyle{fancy}
\raggedbottom
\renewcommand\familydefault{\sfdefault}
\newcommand{\helv}{%
\fontfamily{phv}\fontseries{m}\fontsize{8}{10}\selectfont}
\newcommand{\mycopyright}{\helv Copyright.}
\cfoot{\mycopyright}
\rhead{\textbf{\Sexpr{firstname} \Sexpr{lastname}} \\ \Sexpr{oafr} to \Sexpr{eoafr} \\ Page \thepage}
\renewcommand{\headrulewidth}{0.4pt}
\renewcommand{\footrulewidth}{0.4pt}
\fancypagestyle{fancytitlepage}
{
\fancyhf{}
\cfoot{\mycopyright}
\rhead{}
\renewcommand{\headrulewidth}{0pt}
}
\linespread{1.2}
\usepackage{sectsty}
\allsectionsfont{\sffamily}
\partfont{\centering}
\makeatletter
\newcommand{\sectbox}[1]{%
\noindent\protect\colorbox{gray!40}{%
\#tempdima=\hsize
\advance\#tempdima by-2\fboxsep
\advance\#tempdima by-2\fboxrule
\protect\parbox{\#tempdima}{%
\smallskip
% extra commands here
\centering
#1\smallskip
}}}
\newcommand{\subsectbox}[1]{%
\noindent\protect\colorbox{gray!20}{%
\#tempdima=\hsize
\advance\#tempdima by-2\fboxsep
\advance\#tempdima by-2\fboxrule
\protect\parbox{\#tempdima}{%
\smallskip
% extra commands here
#1\smallskip
}}}
\makeatother
\sectionfont{\sectbox}
\subsubsectionfont{\subsectbox}
\makeatletter
\newcommand\cellwidth{\TX#col#width}
\makeatother
\newlength\foo
\NewEnviron{recipe}{%
\begin{adjustbox}{minipage=\linewidth,gstore totalheight=\foo, gobble}
\BODY
\end{adjustbox}
\needspace{\foo}
\BODY%
}
<<setup, echo=FALSE >>=
opts_chunk$set(fig.path = tempfile(tmpdir="work",pattern=fname))
#
\hyphenpenalty=100000
\begin{document}
\raggedbottom
\setlength{\parskip}{0pt}
<<custom-dev,echo=FALSE>>=
wkld_pdf<-function(file,width,height) {
pdf(file,width=5,height=2)
}
#
<<wkld, echo=FALSE, results='asis',fig.align="center",dev="wkld_pdf",fig.ext="pdf">>=
if (!is.na(wkld.team) | !is.na(wkld.res)) {
g<-pltr$workload.chart(wkld.team,wkld.res,firstname)
print(g)
}
#
\end{document}
In the above example, the file work\fname61c28cd1a0awkld-1.pdf is correctly created, but the tex generated has:
{\centering \includegraphics[width=\maxwidth]{work\fname61c28cd1a0awkld-1}
}
and thus doesn't find it.
It appears that leaving out fileext works (and likely setting it to _pdf would as well) to remove the warning.
It was also necessary to replace the \ generated by tempfile with a / to prevent another warning from the generated includegraphics call, as somewhere in the chain, the \ was evaluated down to . This worked:
opts_chunk$set(fig.path = gsub('\\\\','/',tempfile(tmpdir="work",pattern=fname)))
Thank you for helping me track that down.

No author details in pdf, from R-Markdown / LaTeX template

I'm trying to create an R-Markdown template based on the BioMed Central LaTeX template (bmc-article.tex).
The bmc template files are available for download here and needless to say, they work just fine: https://www.biomedcentral.com/authors/tex
In particular, the author, address and note definitions work and produce the desired outcome.
I have replaced the example author, adresse and note definitions in the bmc-article.tex file to use that as a tex template. I have also removed most of the example-content in that file.
The definition examples in the bmc-article.tex, I have replaced with:
$for(author)$
\author[%
addressref={$author.addressref$}, %
$if(author.corref)$corref={$author.corref$}, $endif$ %
$if(author.noteref)$noteref={$author.noteref$}, $endif$ %
email={$author.email$} %
]{\inits{$author.inits$}\fnm{$author.fnm$} \snm{$author.snm$}}
$endfor$
$for(address)$
\address[id=$address.id$]{ %
$if(address.orgname)$ \orgname{$address.orgname$}, $endif$ %
$if(address.street)$ \street{$address.street$}, $endif$ %
$if(address.postcode)$ \postcode{$address.postcode$}, $endif$ %
$if(address.city)$ \city{$address.city$}, $endif$ %
$if(address.cny)$ \cny{$address.cny$}$endif$ %
}
$endfor$
\begin{artnotes}
$for(notes)$
\note[id=$notes.id$]{$notes.text$} % note, connected to author
$endfor$
\end{artnotes}
When 'knitr'ing the Rmd file, it is (as far as I can tell), converted into meningful tex, and I have perused the resulting tex file again and again looking for tex-errors, but find none.
E.g.:
author:
- fnm: "Soren"
snm: "ONeill"
inits: "S"
addressref: "aff1"
email: "sorens mail"
corref: "aff1"
noteref: "n1"
..becomes:
\author[%
addressref={aff1}, %
corref={aff1}, %
noteref={n1}, %
email={sorens mail} %
]{\inits{S}\fnm{Soren} \snm{ONeill}}
The resulting pdf file however is not correct. The superscript numbers which associate names with addresses is displayed as questionmarks and author details at the end of the article is missing altogether.
I fail to see any significant difference between the tex file created by pandoc (based on my Rmd file) and the original bmx template tex file.
The following is rather lengthy I know.
The Rmd example file
title: "Template testing"
author:
- fnm: "Soren"
snm: "ONeill"
inits: "S"
addressref: "aff1"
email: "sorens mail"
corref: "aff1"
noteref: "n1"
- fnm: "Lotte"
snm: "ONeill"
inits: "L"
addressref: "aff2"
email: "lottes mail"
address:
- id: "aff1"
orgname: "University of Southern Denmark"
street: "Campusvej 55"
postcode: "DK 5500"
city: "Odense M"
cny: "Denmark"
- id: "aff2"
orgname: "University of Southern Denmark"
street: "Campusvej 55"
postcode: "DK 5500"
city: "Odense M"
cny: "Denmark"
notes:
- id: "n1"
text: "Equal contributor"
date: "2 jun 2017"
output:
pdf_document:
template: template.tex
keep_tex: TRUE
---
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see rmarkdown.rstudio.com.
This is the template.tex file, which I have adapted from the downloaded bmc-article.tex file
%% BioMed_Central_Tex_Template_v1.06
\documentclass{bmcart}
\usepackage[utf8]{inputenc} %unicode support
\def\includegraphic{}
\def\includegraphics{}
\begin{document}
\begin{frontmatter}
\begin{fmbox}
\dochead{Research}
\title{$title$}
$for(author)$
\author[%
addressref={$author.addressref$}, %
$if(author.corref)$corref={$author.corref$}, $endif$ %
$if(author.noteref)$noteref={$author.noteref$}, $endif$ %
email={$author.email$} %
]{\inits{$author.inits$}\fnm{$author.fnm$} \snm{$author.snm$}}
$endfor$
$for(address)$
\address[id=$address.id$]{ %
$if(address.orgname)$ \orgname{$address.orgname$}, $endif$ %
$if(address.street)$ \street{$address.street$}, $endif$ %
$if(address.postcode)$ \postcode{$address.postcode$}, $endif$ %
$if(address.city)$ \city{$address.city$}, $endif$ %
$if(address.cny)$ \cny{$address.cny$}$endif$ %
}
$endfor$
\begin{artnotes}
$for(notes)$
\note[id=$notes.id$]{$notes.text$} % note, connected to author
$endfor$
\end{artnotes}
\end{fmbox}% comment this for two column layout
\begin{abstractbox}
\begin{abstract} % abstract
\parttitle{First part title} %if any
Text for this section.
\parttitle{Second part title} %if any
Text for this section.
\end{abstract}
\begin{keyword}
\kwd{sample}
\kwd{article}
\kwd{author}
\end{keyword}
\end{abstractbox}
\end{frontmatter}
%$body$
\begin{backmatter}
\section*{Competing interests}
The authors declare that they have no competing interests.
\section*{Author's contributions}
Text for this section \ldots
\section*{Acknowledgements}
Text for this section \ldots
\bibliographystyle{bmc-mathphys} % Style BST file (bmc-mathphys, vancouver, spbasic).
\bibliography{bmc_article} % Bibliography file (usually '*.bib' )
\end{backmatter}
\end{document}
This produces the following tex file (I've instructed RStudio/pandoc to retain the tex file):
%% BioMed_Central_Tex_Template_v1.06
\documentclass{bmcart}
\usepackage[utf8]{inputenc} %unicode support
\def\includegraphic{}
\def\includegraphics{}
\begin{document}
\begin{frontmatter}
\begin{fmbox}
\dochead{Research}
\title{Template testing}
\author[%
addressref={aff1}, %
corref={aff1}, %
noteref={n1}, %
email={sorens mail} %
]{\inits{S}\fnm{Soren} \snm{ONeill}}
\author[%
addressref={aff2}, %
%
%
email={lottes mail} %
]{\inits{L}\fnm{Lotte} \snm{ONeill}}
\address[id=aff1]{ %
\orgname{University of Southern Denmark}, %
\street{Campusvej 55}, %
\postcode{DK 5500}, %
\city{Odense M}, %
\cny{Denmark} %
}
\address[id=aff2]{ %
\orgname{University of Southern Denmark}, %
\street{Campusvej 55}, %
\postcode{DK 5500}, %
\city{Odense M}, %
\cny{Denmark} %
}
\begin{artnotes}
\note[id=n1]{Equal contributor} % note, connected to author
\end{artnotes}
\end{fmbox}% comment this for two column layout
\begin{abstractbox}
\begin{abstract} % abstract
\parttitle{First part title} %if any
Text for this section.
\parttitle{Second part title} %if any
Text for this section.
\end{abstract}
\begin{keyword}
\kwd{sample}
\kwd{article}
\kwd{author}
\end{keyword}
\end{abstractbox}
\end{frontmatter}
%\subsection{R Markdown}\label{r-markdown}
This is an R Markdown document. Markdown is a simple formatting syntax
for authoring HTML, PDF, and MS Word documents. For more details on
using R Markdown see rmarkdown.rstudio.com.
\begin{backmatter}
\section*{Competing interests}
The authors declare that they have no competing interests.
\section*{Author's contributions}
Text for this section \ldots
\section*{Acknowledgements}
Text for this section \ldots
\bibliographystyle{bmc-mathphys} % Style BST file (bmc-mathphys, vancouver, spbasic).
\bibliography{bmc_article} % Bibliography file (usually '*.bib' )
\end{backmatter}
\end{document}
The latex log file is rather lengthy (lots of stuff about Unicode char's etc), but this is possibly helpful
LaTeX Warning: Reference `aff1thanks' on page 1 undefined on input line 19.
LaTeX Font Info: Try loading font information for OMS+cmss on input line 19.
LaTeX Font Info: No file OMScmss.fd. on input line 19.
LaTeX Font Warning: Font shape `OMS/cmss/m/n' undefined
(Font) using `OMS/cmsy/m/n' instead
(Font) for symbol `textdagger' on input line 19.
LaTeX Warning: Reference `aff2thanks' on page 1 undefined on input line 25.
\address#aff1=\toks21
\address#aff2=\toks22
LaTeX Font Info: External font `cmex10' loaded for size
(Font) <7> on input line 46.
LaTeX Font Info: External font `cmex10' loaded for size
(Font) <5> on input line 46.
LaTeX Warning: Reference `aff1thanks' on page 1 undefined on input line 46.
No file template_test_1.bbl.
AED: lastpage setting LastPage
LaTeX Font Warning: Font shape `OT1/cmss/m/it' in size <8> not available
(Font) Font shape `OT1/cmss/m/sl' tried instead on input line 89.
Overfull \hbox (1.0pt too wide) has occurred while \output is active
[]
[]
[1{/var/lib/texmf/fonts/map/pdftex/updmap/pdftex.map}
] (./template_test_1.aux)
LaTeX Font Warning: Size substitutions with differences
(Font) up to 1.0pt have occurred.
LaTeX Font Warning: Some font shapes were not available, defaults substituted.
LaTeX Warning: There were undefined references.
Of course, I have noticed the warning about "Reference `aff2thanks'", but find no such reference in the original bmx-article.tex
Again, I know this is long -- I apologize for that. I hope someone can make suggestions...

knitr: generating UTF-8 output from chunks

I have a doc.Rnw supposed to produce some Russian UTF-8 strings:
\documentclass{article}
\usepackage{inputenc}
\inputencoding{utf8}
\usepackage[main=english,russian]{babel}
\begin{document}
\selectlanguage {russian}
<<test, results='asis', echo=FALSE>>=
print(readLines('string.rus', encoding="UTF-8"))
print("Здравствуйте")
#
Здравствуйте
\selectlanguage {english}
\end{document}
string.rus has a UTF-8 string which corrrctly shows in R console:
print(readLines('string.rus', encoding="UTF-8"))
# [1] "Здравствуйте"
doc.Rnw coorectly shows in Windows notepad, while both:
file.show("doc.Rnw")
file.show("doc.Rnw", encoding="UTF-8")
fail to show properly the UTF-8 strings.
Using:
knit("doc.Rnw")
The document part of the output doc.tex shows:
\begin{document}
\selectlanguage {russian}
[1] "<U+0417><U+0434><U+0440><U+0430><U+0432><U+0441><U+0442><U+0432><U+0443><U+0439><U+0442><U+0435>"
[1] " <U+0097>д <U+0080>авс <U+0082>в <U+0083>й <U+0082>е"
Здравствуйте
\selectlanguage {english}
\end{document}
which of course does not compile in PDFLaTeX. Using:
knit("doc.Rnw", encoding="UTF-8")
gives even worse results.
Commenting the chunks which should generate UTF-8 strings:
print(readLines('string.rus', encoding="UTF-8"))
print("Здравствуйте")
gives a valid doc.tex which compiles in MikTeX and shows properly the remaining UTF-8 string.
Even if I comment the first print... and leave only the second one. I can't compile. This seems to prove that the original encoding of doc.Rnw is correct.
I tried to replace both print commands with:
a="Здравствуйте"
Encoding(a)="UTF-8"
print(a)
In this case I can compile, but the PDF output is (first string is cut out from margin):
[1] «U+0417><U+0434><U+0440><U+0430><U+0432><U+0441><U+0442><U+0432><U+0443>
Здравствуйте
So the chunk output is still wrong.
How to properly print UTF-8 strings from chunks?
R version is 3.3.3 (2017-03-06) for Windows and knitr is 1.15.1 (2016-11-22).
An extended working example is below:
\documentclass{article}
\usepackage{inputenc}
\inputencoding{utf8}
\usepackage[main=english,russian]{babel}
\begin{document}
\selectlanguage {russian}
<<test, results='asis', echo=FALSE>>=
s=readLines('string.rus', , encoding="UTF-8")
message("s ", Encoding(s), ": ", s)
Encoding(s)="latin1"
message("s latin1: ", s)
Encoding(s)="unkwnown"
message("s unkwnown: ", s)
Encoding(s)="utf8"
message("s utf8: ", a)
a="Здравствуйте"
message("a ", Encoding(a), ": ", a)
Encoding(a)="latin1"
message("a latin1: ", a)
Encoding(a)="utf8"
message("a utf8: ", a)
Encoding(a)="UTF-8"
message("a UTF-8: ", a)
u=("\U0417")
message("u ", Encoding(u), ": ", u)
Encoding(u)="latin1"
message("u latin1: ", u)
Encoding(u)="unkwnown"
message("u unkwnown: ", u)
#
Здравствуйте
\selectlanguage {english}
\end{document}
After knit("doc.Rnw", this is the output related to test chunk found in doc.tex (without knitr code decoration for readability):
s UTF-8: <U+0417><U+0434><U+0440><U+0430><U+0432><U+0441><U+0442><U+0432><U+0443><U+0439><U+0442><U+0435>
s latin1: Здравствуйте
s unkwnown: Здравствуйте
s utf8: <U+0417><U+0434><U+0440><U+0430><U+0432><U+0441><U+0442><U+0432><U+0443><U+0439><U+0442><U+0435>
a unknown: Здравствуйте
a latin1: Здравствуйте
a utf8: Здравствуйте
a UTF-8: <U+0417><U+0434><U+0440><U+0430><U+0432><U+0441><U+0442><U+0432><U+0443><U+0439><U+0442><U+0435>
u UTF-8: <U+0417>
u latin1: З
u unkwnown: З
Some comments follow.
First, only message() works, print() gives always errors.
In both the externally read string s and the locally set a, the behavior is weird.
in fact, keeping or explicitly setting the code to UTF-8 produces the wrong results (utf8 works for a).
One might think the UTF8 encoding of the documents (doc.Rnw and string.rus) is not properly set. This is why I added the line u=("\U0417"), which is UTF8 for sure. Again, only removing the UTF8 encoding gives a proper output.
In a simialr fashion, requesting explicitly an UTF8 output:
knit("doc.Rnw", encoding="UTF-8")
does not produce the UTF8 charaters, but their unicode values or weird ones.
In the end, I can produce the desired .tex file and compile the LaTeX it, but why there is the above counter-intuitive behavior is beyond me.
Hopefully someone will give a good explanation.

Resources