problems plotting special characters (slovene) to knitr latex reports - r

I'm having trouble printing special characters (ščž) to a pdf report made by knitr.
\documentclass[a4paper, 12pt, oneside]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[slovene]{babel}
\begin{document}
<<>>=
plot(runif(100), main = "ŠČĆŽ ščćž")
#
\end{document}

Based on comments by Yihui (see also comments below), here's a solution that worked for me. The .Rnw document I'm working with is encoded as UTF-8.
The key is to specify encoding to knit.
Notice that we're still missing the "č" (for non-native speakers, you can read this character as "ch").
The issue can be resolved by specifying a different printing device. Consider specifying dev = "CairoPDF" (requires additional CairoPDF package) or dev = "cairo_pdf" (requires no additional packages) in your chunk option.
<<dev = "CairoPDF">>=
plot(runif(100), main = "ŠČĆŽ ščćž")
#
or
<<dev = "cairo_pdf">>=
plot(runif(100), main = "ŠČĆŽ ščćž")
#
If you're using Eclipse + StatET to weave your reports, you can set these options to automate the workflow.

Related

run an R Markdown (check.Rmd ) and an R knitr (test.Rnw ) file together

I have the following problem; There are 2 big documents, one written in R Markdown (check.Rmd ) and the other in R knitr (test.Rnw ). In the first doc we have a code like the following:
\section{Organisations Test}
\textbf{Running Organisations Checks}
<<CreateOrganisations, echo=FALSE, progress=TRUE, warning=FALSE, eval=TRUE>>=
source("OrganisationsTest.R")
OrganisationsTest(current_schema,server,user,pass)
#
and in the other as follows:
2. check the downwards shock
```{r chunk_Int_Sh_p2, echo=FALSE}
unique(param.int.shock.tab[SHOCKTYPE=="SHOCK_DOWN"&PERIODEND<21|PERIODEND==90, list( Maturity=PERIODEND, Shock_value=100*SHOCKVALUE)])
```
Now the question: how can I combine both so that I have just one script which runs and compile both one after each other. Just for clarification, I mean without any changes in both documents how can I have just one script which applyes to the first doc knit PDF to create pdf and to the other one CompilePDF ?
I suppose in Linux one can write a shell script but what a bout using RStudio in windowes?
I am really grateful for every hint I am a little bit helpless!
Addendum: In principle it is as follows: we have 2 files if you would compile a knitr file you would use bottom in RStudio, and for a Markdown file one may use bottom in RStudio, BUT we want to put both together and klick on one bottom. How is it possible?
The RStudio buttons "Compile PDF" (for RNW documents) and "Knit PDF" (for RMD documents) are convenient, but in cases like this one it is important to understand what they do in order to reproduce the same or similar behavior.
Summing the question up, it asks for a way to convert two files (a RMD and a RNW document) to PDF, preferably using a button like the two buttons mentioned above.
Unfortunately, (up to my knowledge) it is not possible to add any user-defined buttons to the RStudio GUI. But it is straightforward to write an R script that compiles both documents.
In the following I assume two files:
first.Rmd:
This is a RMD file.
```{r, echo=FALSE}
plot(1)
```
second.Rnw:
\documentclass{article}
\begin{document}
This is a RNW file.
<<>>=
plot(1)
#
\end{document}
To compile first.Rmd to PDF, we need the following (see How to convert R Markdown to PDF?):
library(knitr)
library(rmarkdown)
knit(input = "first.Rmd")
render(input = "first.md", output_format = "pdf_document")
The knit call generates first.md from first.Rmd, execting the R code in the chunks. render converts the resulting markdown file to PDF. [Note the addendum at the bottom!]
To compile first.Rnw to PDF, we can simply use knit2pdf:
knit2pdf("second.Rnw")
Copying both snippets into one R script and clicking "Source" is as close as possible to a "one-button-solution".
However, note that the snippets do something very similar to the "Compile / knit PDF" button, but it is not identical. The "Compile" buttons start a new R session while the solution above uses the current session.
Before executing the snippets make sure to use the correct working directory.
Both knit and knit2pdf by default use envir = parent.frame(). That means R code in chunks is executed in the calling enironment (see What is the difference between parent.frame() and parent.env() in R). This can be a useful feature, for example to "pass" variables to chunks, but it is important to know about it. Otherwise a document might compile just fine in one session (where certain variables exist in the calling environment) but cannot be compiled in another session (that is missing these variables). Therefore, this feature is a little bit dangerous in terms of reproducibility. As a solution, envir = new.env(parent = as.environment(2)) could be used; see knitr inherits variables from a user's environment, even with envir = new.env() for more details on that topic.
I just realized to following about render:
If the input requires knitting then knit is called prior to pandoc.
(Source: ?render)
Therefore, knit(input = "first.Rmd"); render(input = "first.md", output_format = "pdf_document") can be simplified to render(input = "first.Rmd", output_format = "pdf_document"). The envir issues of knit from above apply to render as well.

With knitr and .Rnw for LaTeX, how do you print the full bibliography in PDF output?

I can't seem to hack my way through all the possibilities and have a full bibliography inserted in the PDF output of RStudio, knitr, an .Rnw script, and the "Compile PDF" button. The desired text in the PDF would be the details of the cited works.
Here is a Lilliputian bibtex file, called jabrefbibtest.bib, saved in the working directory.
#Book{GreentargetEngagement2012,
Title = {"2012 - In - House Counsel New Media Engagement Survey"},
Author = {"Inside Counsel "},
Publisher = {"Greentarget"},
Year = {"2012"},
Pages = {"20"},
Plots = {"9"},
Tables = {"0"},
Url = {"http://www.greentarget.com/wp-content/uploads/2012/01/2012GTZGICSurveyReportFinal-WebsiteVersion.pdf"}
}
#Book{CitiprivateBank,
Title = {"Intellectual Leadership with Law Watch"},
Author = {""},
Publisher = {""},
Year = {"2008"},
Pages = {"2"},
Plots = {"1"},
Tables = {"4"},
Url = {"http://www.citigroup.com/privatebank/lawassociates/pdfs/lawwatch/slipsheet.pdf"}
}
The .Rnw script, stripped down, is
\documentclass[11pt]{article}
\usepackage[backend=bibtex]{biblatex}
% \addbibresource{} # not sure if this is needed
\begin{document}
<<bibbackground, echo=FALSE, include=FALSE>>=
setwd("~/R/knitr docs/")
Sys.setenv(TEXINPUTS=getwd(),
BIBINPUTS=getwd(),
BSTINPUTS=getwd())
#
\bibliographystyle{plain}
\bibliography{jabrefbibtest}
Here is one citation \cite{GreentargetEngagement2012} and here is a second \cite{CitiprivateBank}.
Now do full References show below?
\printbibliography
\end{document}
The log:
! Package biblatex Error: '\bibliographystyle' invalid.
See the biblatex package documentation for explanation.
Type H <return> for immediate help.
...
l.59 \bibliographystyle{plain}
Use the package option 'style' instead.
I'm ignoring this command.
! LaTeX Error: Can be used only in preamble.
See the LaTeX manual or LaTeX Companion for explanation.
Type H <return> for immediate help.
...
l.60 \bibliography
{jabrefbibtest}
Your command was ignored.
Type I <command> <return> to replace it with another command,
or <return> to continue without it.
LaTeX Warning: Citation 'GreentargetEngagement2012' on page 1 undefined on inpu
t line 62.
[more omitted]
Along with The Latex Companion, Dynamic Documents with R and knitr, by Yihui Xie, two LaTeX primers and the 262-page manual for biblatex I have struggled through the complicated advice of these sites. Fruitlessly.
https://tex.stackexchange.com/questions/71565/knitr-and-biblatex
https://tex.stackexchange.com/questions/63852/question-mark-instead-of-citation-number
http://texblog.org/2013/08/20/rknitr-automatic-bibliography-generation-with-biblatex-in-rstudio/
http://www.inside-r.org/packages/cran/knitcitations/docs/bibliography
EDIT after COMMENTS
All the PDF file has is this:
References
Here is one citation [?] and here is a second [?].
Now do full References show below?
As the error messages told you:
Don't use \bibliographystyle{plain} (this does not work for biblatex); use the style option in \usepackage[]{biblatex} instead;
\bibliography{jabrefbibtest} must be put in the preamble instead of the body.
After you correct these issues, it should work:
\documentclass[11pt]{article}
\usepackage[backend=bibtex]{biblatex}
\bibliography{jabrefbibtest}
% or use \addbibresource{jabrefbibtest.bib}
\begin{document}
Here is one citation \cite{ABFWomenFirstChairs2015} and
here is a second \cite{ACCGCSkills2013}.
Now do full References show below?
\printbibliography
\end{document}
BTW, RStudio probably does not support the default backend biber of biblatex, so the backend=bibtex option was used.
I use exactly this setup below to get (note I'm not a fan of changing wd in knitr/rmarkdown and removed this; also your keys in the Rnw didn't match the key in the mwe):
\documentclass[11pt]{article}
\usepackage[american]{babel}
\usepackage[style=apa,backend=biber,bibencoding=latin1]{biblatex}
\DeclareLanguageMapping{american}{american-apa}
\addbibresource{jabrefbibtest.bib}
\begin{document}
<<bibbackground, echo=FALSE, include=FALSE>>=
#setwd("~/R/knitr docs/")
Sys.setenv(TEXINPUTS=getwd(),
BIBINPUTS=getwd(),
BSTINPUTS=getwd())
#
%\bibliographystyle{plain}
Here is one citation \cite{GreentargetEngagement2012} and here is a second \cite{CitiprivateBank}.
Now do full References show below?
\printbibliography
\end{document}
Also after the Rnw knits I have to run the tex file though a LaTeX compiler to render the references the first time.
I always just place \bibliography{jabrefbibtest} at the end of the script where I want the references to occur.
To include all references from your .bib file in your bibliography, i.e. even ones that you didn't end up citing, include the line
\nocite{*} right before the line \printbibliography

KnitR XeTeX Beamer issue

I am trying to use a Beamer theme that requires \usepackage[no-math]{fontspec} with a KnitR document. Here is a minimal example test.Rnw:
\documentclass[handout]{beamer}
\usepackage[no-math]{fontspec}
\begin{document}
\maketitle
<<include=FALSE>>=
options(tikzDefaultEngine='xetex')
#
\begin{frame}{test}
\begin{figure}[htbp]
<<echo=FALSE, dev="tikz">>=
plot(1:100)
#
\end{figure}
\end{frame}
\end{document}
When I Knit the doucument I get:
Error in getMetricsFromLatex(TeXMetrics) :
TeX was unable to calculate metrics for the following string
or character:
m
Common reasons for failure include:
* The string contains a character which is special to LaTeX unless
escaped properly, such as % or $.
* The string makes use of LaTeX commands provided by a package and
the tikzDevice was not told to load the package.
This is an issue specifically related to the no-math option with fontspec along with dev="tikz". If I remove either of these, the document compiles fine. Any suggestions on how to get this to work? The entire purpose of using a tikz device is to allow the format of my graphics to match up with my theme that requires I am trying to use a Beamer theme that requires \usepackage[no-math]{fontspec}. Thanks!

Dynamic LaTeX references in R comment with knitr

I had ask a similar question to this with respect to Sweave (
Dynamic references to figures in a R comment within Sweave document
) and would like to see if anyone as a similar answer when using knitr.
The goal is to have the following code chunk
<<"example", fig.cap = "some figure", highlight = FALSE>>=
# the following code generated Figure \ref{fig:example}
plot(1:10, 1:10)
#
have be displayed in the resulting .pdf as
# the following code generated Figure 1.1
plot(1:10, 1:10)
So far I have found that by setting highlight = FALSE the R code is placed into a verbatim environment in the resulting .tex file. If the environment could be alltt instead of verbatim then we'd have the desired output. Is it possible to have the non-highlighted code chunks be placed in alltt environments via a knitr option?
I have added an example 072-latex-reference.Rnw in the knitr-examples repository. The basic idea is to restore the escaped \ref{} (which should have been \textbackslash{}ref\{\} in the default output).

Getting Sweave code chunks inside some framed box?

I would like to make an R code chunk (in Sweave) printed inside a framed box in the resulting pdf.
Is there an easy solution for doing that?
The short answer is that yes, there is an easy way. Just add the following lines, or something like them to the preamble of your Sweave document:
\DefineVerbatimEnvironment{Sinput}{Verbatim} {xleftmargin=2em,
frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{xleftmargin=2em,
frame=single}
This works because the appearance of code (and output) chunks is controlled by the definition of the Sinput and Soutput environments. These are both Verbatim environments as provided by the LaTeX package fancyvrb. (Click here for a 73 page pdf describing the numerous options that fancyvrb provides).
A quick look in the file Sweave.sty reveals the default definition of those two environments:
\DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{}
\DefineVerbatimEnvironment{Scode}{Verbatim}{fontshape=sl}
To change those definitions, just add \DefineVerbatimEnvironment statements of your own devising either: (a) at the end of the Sweave.sty file; or (b) at the start of your *.Snw document.
Finally, here's an example to show what this looks like in practice:
\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))
#
\end{document}
knitr, a successor of Sweave, by default outputs all echoed R code in boxes, and also formats it to the margins. Other nice features include syntax coloring and PGF integration.
Sweave code of average complexity needs only minor if any adaptions to run with knitr.

Resources