RMarkdown: how to print formula inline - r

Given a linear model:
fit <- lm(mpg~., mtcars)
I tried `r formula(fit)` to print the model/formula inline, but trying to knit the RMarkdown file to PDF or HTML gives errors (error in vapply...)
If it do the same thing inside a triple quoted code chunk, it works fine:
```{r}
formula(fit)
```
formula(fit) prints the formula on the R interpreter as I would like.
Is there a limitation to what can be done in an inline code chunk, or am I missing something?

I don't know why exactly, but I think the issue lies in the structure and formatting of a formula-object. I'm guessing that the objects get converted to character in order to be printed. This is why it works (albeit in a weird sequence) for one independent variable, but doesn't work for multiple independent variables.
A workaround is to use
`r format(formula(fit))`
As inline code, it gave me the desired result.

Related

Create Quarto or R Markdown Document Code Chunk with Source Code Stored as Element in a Vector

I'm wondering if someone might be able to help figure out how (if it's possible) to take source code stored in a vector in R and pass it to a code chunk or code block in Quarto or Markdown. Essentially what I'm trying to do is the same thing as reading the source for an code chunk from an external data file using the file= option for a code chunk, but instead of pointing it to an external file containing my source, I wanted to pull the source from a vector element.
So for example, if I had a file called myfile.R that contained the following R code:
x <- rnorm(100)
hist(x)
And I wanted to pull this code into a code block and render it in Quarto or R, I could simply use:
```{R, echo=TRUE, file="myfile.R"}
```
And this would create a Quarto/Markdown document that prints the contents of myfile.R and then produces a histogram. However, what if the code is not stored in an external file but in an element of a vector in R? For example, say, I have the same code that was stored in myfile.R, only it's stored as a character variable inside source_code_vector, along with possibly some other elements containing source code as well:
source_code_vector <- c("x <- rnorm(100) hist(x)", "y<-rpois(100, 5) hist(y)")
How can I access this code in the first element of source_code_vector and pass it into the code chunk? I'd imagine it would be something along the lines of this (but this is obviously not right since the code isn't stored in a file but in a vector):
```{R, echo=TRUE, file=source_code[1]}
```
I realize I could always write out the value of the element to a text file and then read back in the text file into the code chunk, but this seems very inefficient, and I imagine there's a much better way to do this?
Thanks.
You can use the chunk option code instead of file: https://yihui.org/knitr/options/#code-chunk
```{r, code=source_code_vector[1]}
```

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.

Is there any way to execute some R code inside a "cat()" function inside a chunk in a R Markdown document?

Can anyone help me out?
I have to automate some reports, with R Markdown, of the company I work for.
To do so, I have to create headings with the names of forest gardens, deppending on the forest gardens that were evaluated last month.
The problem is that the numbers of forests gradens evaluated every month is not the same.
So, I added a condition to run on chunk option "eval" to create that heading deppending on the number of the evaluated forest gardens (it's ok until here).
To do so, I wrote this code:
```{r eval = cond_n1, results = 'asis'}
cat('<h4 class = "hortos"> 4.1. `r unique(tabela_por_talhao$NM_HORTO[1])`</h4>')
```#end
But when I knitr the document every thing works very fine, but the inline code that I inserted in this heading doesn't, it prints the code literatelly (without execute).
Is there any way to do what I want?
OBS: I only added the "#end" to the end of the chunk because otherwise it won't show here the whole code.

Markdown output not fitting column

I'm writing an article in RStudio (global setting is using knitr) trying to make the output generated by a chunk of code fit the specification of the IEEE jornal, butthe output will wonder off the column (text is organized in two columns).
I've tried specifying the out.width of the code chunk with the column width (out.width="\columnwidth") but it doesn't seem to do much. I've also tried specifying the same parameter with "\linewidth" and "\textwidth" but still I get the same output to the pdf. I've also tried scaling down the size by puting in "%10" and "1%" but no sucess.
<>=
levels(classObito$estado_fisico)
#
Expected the output of the code chunk to fit into the column, but it wonders off the page or to the other column.
Solved with adding option(width="50") inside the code chunk

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.

Resources