Formatting R output in an R Markdown documents - r

I have a code that generates a text output. For example:
pick <- sample(c("Alex", "Greta", "Zoe"), 1)
Is there a way of formatting the result in an R Markdown documents.
Say something like this if I wanted it to appear in bold on the report.
**pick**

You can execute any R command in-text in an rmarkdown document without embedding it inside a chunk by placing it within ticks prefaced by the letter r (see below). You can then surround this r code with latex code, in this \bf{foo} for bold font, bookmarked by $. Try placing
The OP's chosen name is $\bf{`r sample(c("Alex", "Greta", "Zoe"), 1)`}$
inside an rmarkdown document. Or you could place the function in a chunk and then call it outside the chunk, anywhere in subsequent text, like this
The OP's chosen name is $\bf{`r pick`}$

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.

Changing keywords to highlight in an RMarkdown document

I have been writing a document in bookdown where within the *.Rmd file I call a figure by using the following syntax
\#ref(fig:MyFigureName)
This differs slightly from the notation that you would use in a normal RMarkdown file exporting to latex which would be
\ref{fig:MyFigureName}
The issue I am running into is that when I write something in bookdown the function calling the Figure is not being highlighted properly (see image below).
I have imported my own rsTheme (which is from my understanding, basically a .css file) but I don't see an option to add keywords to highlight.
But I would like for the entire function to be colored differently from the inline text (Photoshop version of desired output shown below)
Does anyone know how I would edit my *rsTheme file in order to accomplish this?
Thanks!

Can kable read latex commands?

I have a table that contains cells with latex commands. For instance, one column header reads "\textit{Quantity}."
When I call kable on the table with the following code, the latex command (i.e., "\textit{Quantity}") appears in my document:
knitr::kable(table, format="latex")
When I change the format to "markdown", then the latex command gets interpreted (i.e., Quantity shows up in italics):
knitr::kable(table, format="markdown")
Is there any way to keep format="latex" but get the results of format="markdown"? I.e., I want the latex commands to be interpreted.
Yes, it can.
See the below example:
data2$Physics<-c('$\frac{7}{20}$')
Kable(data2$Physics)
Display the above inside kable , you will see latex equation displayed correctly.

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.

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.

Resources