How to automatically create BibTex citations for R packages in knitr file? - r

I am not sure whether this an R, LaTeX, or BibTex problem.
I am trying to automatically generate a .bib file containing citations for R packages and then list them at the end. I am able to generate the BibTex file and I don't see anything wrong with the BibTex file, but the entries don't appear when I compile the PDF.
I'm not sure if R is not producing a BibTex file correctly, if some LaTeX syntax is wrong, or if the BibTex file needs to be pre-compiled or whatever. I noticed that \bibliography{NOT A REAL FILENAME} will produce a References section without complaining, but I don't think that is the problem.
Minimal working example:
\documentclass[10pt]{amsart}
\usepackage[margin=1in, headheight=20pt, footskip=20pt]{geometry}
\begin{document}
<<label='Create References'>>=
require(knitr) # Needed for write_bib()
# Load some packages to the session:
require(xtable)
require(ggplot2)
# Select packages to cite:
citPkgs <- names(sessionInfo()$otherPkgs)
# Write the bibtex file:
write_bib(citPkgs, file="R-Pckgs.bib")
#
\nocite{*}
\bibliographystyle{plain}
\bibliography{R-Pckgs.bib}
\end{document}
Any help or suggestions would be appreciated.

Just replace \bibliography{R-Pckgs.bib} with \bibliography{R-Pckgs}, and it should work fine.
On Windows 7, with an up-to-date MikTeX installation and current R and R packages, the following worked:
Put your reproducible example in a file named "eg.Rnw" and edit to remove the extraneous ".bib"
Launch R and navigate to the directory in which "eg.Rnw" is located.
Do library(knitr); knit2pdf("eg.Rnw")
Note: There are obviously many workflows for going from *.Rnw to *.pdf, but if you want to use knit2pdf() (at least), make sure that you run it from the directory containing the *.Rnw to be processed.

Add a \nocite{dummycite} to your document - to create a citation so that the bibliography is printed.
Note that this is obsolete if you already have other citation in your document.

Related

Get single latex file instead of PDF for documentation of R package

I would like to get the Latex source for the PDF that is built when executing
R CMD Rd2pdf /path/to/mypackage
for building the R package documentation.
It would be very nice if I could get the documentation as a latex document such that I could easily include it in another latex document as an appendix and have a continuous page numbering.
I have only seen the possibility to compile the files one by one from .Rd to .tex:
How to create R documentation file (.Rd) in latex?, which points to the function tools::Rd2latex and the question How do I convert Rd files to pdf for a package that I am creating in R? which points to the command
R CMD Rdconv -o x.tex --type=latex man/x.Rd
Both commands only work on single .Rd files. The created files lack the header/definitions. So I would have to sort and include each file manually in the final latex file. It would be nice if there is some way to get the latex document in a simpler way.
You can do:
R CMD Rd2pdf path/to/package/man --no-clean
In addition to the PDF file, this creates a folder containing the auxiliary files, including the tex source file.

Pandoc problem with graph in conversion tex to docx

I am having problem in conversion from .tex file to .docx file using pandoc. I used textdoc with stata to get the tex file. Tabularx tables dont display in the docx file, but my biggest problem is with graph that dont display in final document (docx). Lamentably the person that receive the final document need a docx. file
I am using pandoc for windows and runing from cmd windows.
pandoc -s tesis.tex -o output.docx
I tried with others indirect type of conversion:
pandoc -s tesis.tex -o output2.html
pandoc -s output2.html -o output6.docx
In other way I am able to use knitr with R to make a .tex file, but I dont if its possible to get a docx file with this method.
Thanks in advance
Providing more information, as suggested in my comment and the wiki for the stata tag will allow folks to provide better answers. However, since your problem seems to be with the treatment of the graph in particular you can start by:
Checking how texdoc is handling the graph. The default appears to be .pdf
Make sure any \includegraphics Or similar references in thesis.tex include the .pdf extension. See this discussion for more information

Latex and Sweave, cannot include figure

I have a file for my thesis, which include the chapters.
A few weeks ago, I worked with R-Statistic and *.rnw files to produce a *.tex paper.
Now, I want to include these *.tex paper in my thesis. However, every time I get several errors.
Structure
/home/UserName/R-files/Dokumentation5.rnw
/home/UserName/tex-Files/Dokumentation5.tex // from Dokumentation5.rnw files
In the following folder, I put the TeX and the figures (*.pdf).
/home/UserName/Documentation/chapter/
Edit the Dokumentation5.tex, remove the beginning and "end document"
In thesis file, I added the following commands:
\usepackage{Sweave} \include /home/UserName/Documentation/chapter/
run latex
If I run LaTeX, I got several errors like:
File `Dokumentation5-004' not found.
\begin{document} ended by \end{Schunk}.
Too many }'s
File `Dokumentation5-033' not found.
Create a file master.Rnw that contains nothing but the LaTeX setup (packages to be used, geometry, title, begin/end document, bibliography style and file......)
If you need to use R functions in various places in your paper, create a file func.Rnw where you create these functions. Make this file the first to \SweaveInput{func.Rnw} in your master.Rnw - see here for details
Now create one file for each "unit" of your paper (chapter, section, whatever you like). Make them all chapX.Rnw files, whether they contain R code or not.
\SweaveInput{chapX.Rnw} them in the desired order in your master.Rnw file.
At any time during the process, run Sweave("master.Rnw") in R and then pdflatex master.tex from the console to see what you have produced.

How to convert R Markdown to HTML? I.e., What does "Knit HTML" do in Rstudio 0.96?

What commands are run when pressing "Knit HTML" on an R Markdown file in Rstudio 0.96?
My motivation is that I might want to run the same command when I'm in another text editing environment or I might want to combine the command in a larger makefile.
Basic Script
So now that the R markdown package has been released, here is some code to replicate the features of Knit to Html.
require(knitr) # required for knitting from rmd to md
require(markdown) # required for md to html
knit('test.rmd', 'test.md') # creates md file
markdownToHTML('test.md', 'test.html') # creates html file
browseURL(paste('file://', file.path(getwd(),'test.html'), sep='')) # open file in browser
where test.rmd is the name of your R markdown file.
Note that I'm not 100% confident about the browseURL line (hence my question here about opening files in a web browser).
markdownToHTML Options
The good thing about markdownToHTML is that there are heaps of options in how the HTML is created (see ?markdownHTMLOptions). So for example, if you want just a code fragment without all the header information, you could write:
markdownToHTML('test.md', 'test.html', options='fragment_only')
or if you don't like hard wrapping (i.e., inserting line breaks when there are single manual line breaks in the markdown source), you can omit the 'hard_wrap' option.
# The default options are 'hard_wrap', 'use_xhtml',
# 'smartypants', and 'base64_images'.
markdownToHTML('test.md', 'test.html',
options=c('use_xhtml', 'base64_images'))
Makefile
This could also all be added to a makefile perhaps using Rscript -e (e.g., something like this). Here's a basic example makefile I put together, where test indicates that the rmd file is called test.rmd.
RMDFILE=test
html :
Rscript -e "require(knitr); require(markdown); knit('$(RMDFILE).rmd', '$(RMDFILE).md'); markdownToHTML('$(RMDFILE).md', '$(RMDFILE).html', options=c('use_xhtml', 'base64_images')); browseURL(paste('file://', file.path(getwd(),'$(RMDFILE).html'), sep=''))"
The makefile uses my preferred markdown options: i.e., options=c('use_xhtml', 'base64_images')
Put Sys.sleep(30) in a chunk and you will see clearly what commands are called by RStudio. Basically they are
library(knitr); knit() to get the markdown file;
RStudio has internal functions to convert markdown to HTML;
The second step will be more transparent in the next version of the markdown package. Currently you can use knitr::knit2html('your_file.Rmd') to get a similar HTML file as RStudio gives you.
Update on 2019/09/17: The above answer applies to RStudio v0.96 (in the year 2012). Now R Markdown is compiled through rmarkdown::render(), which uses Pandoc instead of the retired R package markdown. See the post Relationship between R Markdown, Knitr, Pandoc, and Bookdown for more details.
Very easy command line method from knitr in a knutshell:
R -e "rmarkdown::render('knitr_example.Rmd')"
This requires rmarkdown to be installed with install.packages(rmarkdown) and that pandoc is installed (apparently it comes with Rstudio, see knitr in a knutshell for more details).
So far when I've used this it nicely puts all the plots in the HTML file rather than as images in a figure directory and cleans up any intermediate files, if any; just like compilation in RStudio does.
It seems you should call rmarkdown::render() instead of knitr::knit2html() because a.rmd appears to be an R Markdown v2 document.

How do I Sweave a multiple-file project?

I am writing my thesis in LaTeX and because things got a bit long for my taste, I had split it into several files. Let's call them thesis.tex, intro.tex, mat_n_met.tex, rslts.tex and discsn.tex. I have linked intro.tex, mat_n_met.tex, rslts.tex and discsn.tex through thesis.tex with \include{intro} (and so on...).
I have also created a separate file called r_crunching.Rnw (that I run through Sweave) that holds a chunk that runs the R script with data analysis and chunks that produce pdf outputs of graphs that I embed via \includegraphics (in e.g., rslts.tex). Still following?
If I run a Rnw (i.e. I renamed rslts.tex to rslts.Rnw) without "a link" to the chunk with the R script, you will get a Sweave() error saying the reference in \Sexpr{} doesn't exist. Is there a way, without merging all the files into a single .Rnw, to call \Sexpr{} in say rslts.Rnw?
Other methods how to accomplish this are welcome.
I recommend using RStudio (http://www.rstudio.com/ide/). Sweave is nicely integrated into that IDE and it supports multi-file documents. Even Synctex and TeX error log navigation still work when working with multi-file documents.
From the master file you can include child files using
\SweaveInput{Child.Rnw}
You can link a child file back to the master file by including the directive
% !Rnw root = Master.Rnw
in the child file. That way when working on a child file and typesetting it, RStudio know to typeset the master file.
The details are explained in the RStudio documentation at http://www.rstudio.com/ide/docs/authoring/multiple_rnw_files
Forget for a second that you are dealing with Sweave and just think of the latex problem -- for which \include and \includeonly offer solutions. Try that with a few simple test files.
Once you have that figured out, fold Sweave back into the mix and it just work as Sweave is after 'merely' a pre-processing step, albeit a very clever one.
To expand Dirk's and mjm's answer, I would suggest using \include's and Makefiles.
Suppose you have a master file: master.tex. In that file, you include some .tex and .Rnw files, i.e.
\include chapter1
\include chapter2
\include chapter3
....
Now the following Makefile provides functions for creating the .tex, .R and .pdf files:
.SUFFIXES: .tex .pdf .Rnw .R
MAIN = master
##List your your .Rnw includes
RNWINCLUDES = chapter1 chapter2 chapter3
TEX = $(RNWINCLUDES:=.tex)
RFILES = $(RNWINCLUDES:=.R)
RNWFILES = $(INCLUDES:=.Rnw)
all: $(MAIN).pdf
$(MAIN).pdf: $(TEX) $(MAIN).tex
R: $(RFILES)
.Rnw.R:
R CMD Stangle $<
.Rnw.tex:
R CMD Sweave $<
.tex.pdf:
pdflatex $<
bibtex $*
pdflatex $<
pdflatex $<
Essentially, the .SUFFIXES provide a set of rules for convert from one file format to another. For example, to convert from .Rnw to .R, we use the command
`R CMD Stangle $<`
one fairly obvious answer is to use a makefile, possibly using package cachesweave, to process the relevant files in the right order.
My solution to multi-file projects in Sweave (under Rstudio) is the following:
1) Create a master file, say master.Rnw, in which you have the calls to the subfiles intro.Rnw, matmet.Rnw, etc:
\documentclass[11pt]{book}
% \usepackage{blah, blah} as you wish
\graphicspath{ {./figs/}
\begin{document}
\SweaveOpts{concordance=TRUE}
\include{intro} % a call to 'intro.Rnw'
\include{matmet} % a call to 'matmet.Rnw'
\include{results} % a call to 'results.Rnw'
\include{discuss} % a call to 'discuss.Rnw'
\end{document}
2) Create the subfiles. I'm giving here only the first one, intro.Rnw. Please note that in the subfiles you do not use preambular commands such as \documentclass or \begin{document}
\chapter{Introduction}\label{ch:intro}
\section{This is section 01}
In section 01 we are concerned about whether \texttt{Sexpr} could possibly work. The chunk below creates a variable \em{a} which will be referred to by this command later on.
<<>>=
a <- 1+2
#
Ok, if it is working, we shall see number 3 right here: \Sexpr{a}.
3) After saving modifications in 'intro.Rnw', simply go to 'master.Rnw' and compile it using Ctrl+Shift+K and... voilá:
Screenshot of the file created by the above command.

Resources