Define commands for frequently used text in knitr - r

Is there a way to define a command that can be used as a short cut for frequently used text or html commands in knitr when compiling to html?
I use knitr to compile an rmkardown file (.Rmd) and the output is a html file (i.e., I press Knit HTML in RStudio).
To be more specific, let me add an example: I want to separate the percent sign by a hair space from the number before, which I achieve by typing, e.g., 5 %. It would be very convenient, if I could define a command, let's say \perc, that I can use instead, such that 5\perc would be equivalent to 5 %.
Is this at all possible and if yes, how can it be done?

You can define an R function and then call it inline. For example:
```{r}
perc <- function(){
" %"
}
```
This is inline r code 5`r perc()`
I think you could also use it in chunks where the result would be 'asis'.

Related

Print formatted mathematical operations in R

I have in R a mathematical operation like this:
x = 5
y = (x / 5) * 2
and I want to print y to console or pdf file so it looks like:
(x / 5) * 2 like on the paper
Can I do this using R basic functions or some kind of library?
#Yehor: you can use the power of RStudio and RMarkdown to combine text, code, and visualisations in output formats like pdf. Under the hood you need a bit more than "some kind of library". But if you use RStudio as your R editor, the infrastructure (what you need) is actually in place already. RStudio will ask to have a few packages installed when you open a RMarkdown file for the first time, but do not worry about this.
In RStudio open a new RMarkdown file. During the opening dialogue you can (pre-)select an output type, e.g. pdf. Please note that you can change this later.
The example that opens gives you an idea of what you can do. The magic happens when you hit the "knit-button" in the top bar of the editor pane. R/RStudio will render the document and interpret code-chunks. These chunks can include "just" code, code to produce tables and/or graphics.
For math & formulae, RMarkdown supports 2 ways of presenting LATEX:
inline equation
equation mode
(I) inline equation - within single dollar signs $
You can include an inline equation anywhere in the text part of the Rmd document. For example:
This is how I add a formula: $y := \frac{x}{5} * 2$ within a line using inline code.
(II) equation mode - statement within double dollar signs $$
For the equation mode use $$ and have this on a separate line in Rmd.
$$y := \frac{x}{5} * 2$$
Knitting the Rmd in RStudio renders the document into a pdf (you can also export to html, MS Word or even Powerpoint).
For example:
is produced with this minimal Rmd:
If you want to combine this with the calculation, you would add a "code-chunk".
In RMarkdown you can include R-code inside 3 backticks, e.g. {r} # R-stuff ...
Thus, the following code chunks performs the operation:
x <- 5
y <- (x/5) * 2
If you want to print the result "inline" in your text, you can add so-called inline code. This is done by having R-statement inside single backticks and a starting r, i.e. r ... within the text part of the Rmd. For example:
My result is `r y` as inline code.
This will print: My result is 2 as inline code.
You could include more sophisticated R-statements as inline code by separating each statement with a semi-colon (~end of command line). However, I recommend to do the fluffy stuff in a code chunk and use the inline for simple statements. It is much easier on the eye and for debugging.

Aligning XTable Output in R Markdown

I am putting an assignment together in R Markdown to PDF (through Latex) and been using xtable to nicely format my output. The below code generates a small table that I would like to align right in the document and have text wrap around it. Is there a way to achieve this?
summary.table <- xtable(ddply(aircon, ~when, summarise, Mean=mean(hours), StdDev=sd(hours)), caption="Mean and Standard Deviation (in Hours) Before and After Change")
print(summary.table, include.rownames=FALSE)
Given the update regarding using LaTeX to do the wrapping, how could I write this in R Markdown to take advantage of this? I have tried to print inline using r <code> but that didn't work.
I guess you could add the begin/end wraptable commands in the r-chunk that creates the table, like this:
cat("\\begin{wraptable}{r}{5.5cm} \n")
...
print(summary.table,...)
cat("\\end{wraptable} \n")
You can use the Includes mechanism documented here, to include a custom header.tex which would contain usepackages, etc.

Automatically generated LaTeX beamer slides with R/knitr

I am working on a LaTeX report template that automatically generates a beamer document, pulling in figures from specified directories and placing them one per slide.
Here is an example of the code that I am using for this, as a code chunk in my .Rnw document:
<<results='asis',echo=FALSE>>=
suppressPackageStartupMessages(library("Hmisc"))
# get the plots from the common directory
Barplots_dir<-"/home/figure/barplots"
Barplots_files<-dir(Barplots_dir)
# create a beamer slide for each plot
# use R to output LaTeX markup into the document
for(i in 1:length(Barplots_files)){
GroupingName<-gsub("_alignment_barplot.pdf", "", Barplots_files[i]) # strip this from the filename
file <- paste0(Barplots_dir,"/",Barplots_files[i]) # path to the figure
cat("\\subsubsection{", latexTranslate(GroupingName), "}\n", sep="") # don't forget you need double '\\' because one gets eaten by R !!
cat("\\begin{frame}{", latexTranslate(GroupingName), " Alignment Stats}\n", sep="")
cat("\\includegraphics[width=0.9\\linewidth,height=0.9\\textheight,keepaspectratio]{", file, "}\n", sep="")
cat("\\end{frame}\n\n")
}
#
However I recently came across this article by Yihui Xie which includes a remark about cat("\\includegraphics{}") being a bad idea. Is there a reason for this, and is there a better option?
To be clear, these figures are generated by other programs as part of a larger pipeline; generating them within the document is not an option, but I need the document to be able to dynamically find and insert them into the report. I know that there are some capabilities to do this directly from within LaTeX itself but cat'ing out the LaTeX markup I need seemed like an easier and more flexible task.
cat("\\includegraphics{}") is likely to be a bad idea if you are from the old Sweave world (where one might need to open a graphics device, draw a plot, close the device, and cat("\\includegraphics{}")). No kittens will be killed as long as you understand what you are doing. Your use case seems to be very reasonable to me, and I don't have a better approach.

Hmisc tilde rowname

I am trying to group row names in a R data frame for typesetting with the Hmisc latex() function. Problem is that latex() adds two tilde characters before each row name, and these show up in my document.
How can I either remove these characters or have them not show up?
Example:
test.df <- data.frame(row.names=letters[1:4], col1=1:4, col2=4:1, col3=4:7)
latex(test.df, file="", n.rgroup=c(2,2), rgroup=c("First","Second"))
Edit:
The latex function occurs inside a knitr chunk. The resulting .Rnw file is compiled through the knit2pdf function, which uses pdfLatex by default, I think. All other tables/figures in the document compile fine, without any residual LaTex syntax showing up.
They will not show up if you use latex with a TeX processor:
test.df <- data.frame(row.names=letters[1:4], col1=1:4, col2=4:1, col3=4:7)
latex(test.df, file="test", n.rgroup=c(2,2), rgroup=c("First","Second"))
If you want to "capture" the text that is "printed" to the screen and remove the double tildes with sub then you probably need to use capture.output, because it appears that latex is not returning a value but is acting more like the cat function which has output to the screen as a side-effect:
out <- sub("^~~", "", capture.output(
latex(test.df, file="",
n.rgroup=c(2,2), rgroup=c("First","Second"))))
You could then use writeLines or cat with a file argument to send that text to a destination. I suppose it is possible that you could just put the sub call inline without diverting the results to a named object. That will depend on exactly how your are processing this text.
If you don't want to use LaTeX then i suggest either the ascii package that has pretty advanced options that do a nice raw text output (it also has the rgroup & n.rgroup options for grouping row names). If you are interested in getting the tables into a Word document (or just HTML) i suggest Markdown with my htmlTable function - the arguments are based upon the Hmisc latex arguments as I needed a replacement when I was switching to Markdown, thus all you need to do is change the function name to htmlTable after loading my package.

R2HTML or knitr for dynamic report generation?

I want to write an R function which processes some data and then automatically outputs an html report. This report should contain some fixed text, some text changing according to the underlying data and some figures.
What is the best way to go?
R2HTML or knitr?
What are the advantages of one over the other?
As far as I understood R2HTML allows me to build the html file sequentially while knitr already operates on an predefined .Rhtml file.
So, either use R2HTML or stitch and spin from knitr for on the fly report generation.
I would appreciate any suggestions or hints.
I grab this nice opportunity to promote pander a bit :)
This package was written for similar reasons like #Yihui's great knitr, although I wanted to let users really concentrate on the text and R code without dealing with chunk options etc. So letting users generate pretty HTML, pdf or even docx or odt output automatically with some predefined options.
These options affects e.g. the cache engine (handling dependencies without any chunk options) or the default plot options (let it be a "base" R graphics, lattice or ggplot2), so that you do no thave to set the color palette or the minor grid in each of your plots, just once - or live with the package defaults :)
The package captures the results (besides errors/warnings and other messages and the output) of all run R expression and can convert to Pandoc's markdown automatically. There are some helper functions that let you convert the resulting document written in a brew-like syntax automatically to e.g. HTML if you have pandoc installed, or export R objects to markdown/HTML/any other supported format in a live R session with a reference class.
Short demo:
brew file
Pandoc.brew('file_name.brew', output = 'foo.html', convert = 'html')
HTML output
knitr, every time. Handles graphics, lets you write your report with markdown instead of having to write html everywhere (if you want), caches things, makes coffee for you etc.
You can also build an HTML file sequentially as long as you have a decent text editor like Emacs/ESS or RStudio, etc. R2HTML is excellent in terms of its wide support to many R objects (see methods(HTML)), but I'll probably frown on RweaveHTML() due to its root Sweave().
That said, I think it may be a good idea to combine R2HTML and knitr, e.g.
# A LOESS Example
```{r loess-demo, results='asis'}
cars.lo <- loess(dist ~ speed, cars)
library(R2HTML)
HTML(cars.lo, file = '')
```
I was using the R Markdown syntax in the above example. The key is results='asis' which means to writing raw HTML code into the output.
I believe that you can also use Sweave to create HTML files, though I have heard that knitr is easier to use.

Resources