Print formatted mathematical operations in R - 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.

Related

Is it possible to copy one (or 2, or 3) code chunks from one R Markdown document to another R Markdown document without copy/pasting?

I have read previously asked similar questions here, here, and here (among many more).
Unfortunately, none of the solutions offered to those questions seem to solve my issue.
I tried the function written by #bryanshalloway here but that did not have the desired result.
For more context, I am producing scientific manuscripts using an R Markdown workflow. I perform EDA in one notebook and later come back to write the manuscript in a different notebook. I import the data, wrangle it, create tables, and do some basic visualizations in the EDA notebook and include narrative text (mostly for myself).
I then create a separate notebook to write the manuscript. To keep it reproducible, I want to include all of the steps from the EDA with respect to data import, tidying, and wrangling, however I do not need the commentary that went along with it. Additionally, I may want some (but definitely not all) of the tables and basic visualizations I created during the EDA, but I would need to build them up substantially to get them publication ready.
My current workflow is just copying and pasting the relevant code chunks and then adding to those where necessary for tables and figures (i.e., adding labels and captions to a ggplot).
Is there a way to "source" these individual code chunks from one R Markdown file/R Notebook into another? Perhaps using knit_child (but not bring the entire R Markdown file into the current parent file)?
I would like to avoid copying the desired code chunks into separate R scripts.
Thanks!
It is very possible with knitr purl and spin:
Ok lets say this is your initial Rmarkdown report:
call the file report1.Rmd
---
title: Use `purl()` to extract R code
---
The function `knitr::purl()` extracts R code chunks from
a **knitr** document and save the code to an R script.
Below is a simple chunk:
```{r, simple, echo=TRUE}
1 + 1
```
Inline R expressions like `r 2 * pi` are ignored by default.
If you do not want certain code chunks to be extracted,
you can set the chunk option `purl = FALSE`, e.g.,
```{r, ignored, purl=FALSE}
x = rnorm(1000)
```
Then you go to the console and purl the file:
> knitr::purl("report1.Rmd")
this creates an R file called report1.R in the same directory you are in,
with only the chunks that are not purl=false.
Its an simple R script looking like this:
## ---- simple, echo=TRUE----------------------------------------------------------------------------
1 + 1
Lets rename the file for safety purposes:
> file.rename("report1.R", "report_new.R")
Finally lets spin it back to report_new.Rmd :
> knitr::spin("report_new.R", format = "Rmd", knit=F)
This gives you a new Rmd file called report_new.Rmd containing only the relevant chunks and nothing else
```{r simple, echo=TRUE}
1 + 1
```

Formatting R output in an R Markdown documents

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`}$

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.

Define commands for frequently used text in knitr

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'.

How can I write a degree symbol in RMarkdown 2?

I'm writing some code with descriptions using Rmarkdown 2 and knit PDF.
I've been trying many method to write a degree symbol inline:
Latex package: siunitx's \ang
Latex package: textcomp's \textdegree
Latex: \circ
And many possible RMarkdown symbols, such as:
$$ \textdegree $$ or $\textdegree$
But nothing is working. Is there a way to write a degree symbol in RMarkdown 2 and convert it do PDF?
EDIT (18 AUGUST 2014):
Ok, I found out where is the problem. If you use \circ in normal sentence or first-level list it is ok. But when I try to use \circ in second-level list - it's not working.
The problem was with RMarkdown converting nested lists. On this page http://rmarkdown.rstudio.com/authoring_pandoc_markdown.html you can find sentence:
The nested list must be indented four spaces or one tab
Although, using the tab could be a problem. When using four spaces - it works:
* Let's turn this round 360$^\circ$
+ Let's turn this round 360$^\circ$
Using \circ works for me, RStudio, knit to pdf:
Let's turn this round 360$^\circ$
You can use plotmath's degree, e.g.
plot(1, xlab=expression(4*degree))

Resources