How to make the inline output latex ready in Rmd files? - r

I use Rstudio to create my .Rmd documents, in order to combine the markdown ease-of-use with some neat equation support.
I mainly use the inline code syntax `r bla` for evaluation of arguments in an equation (between $...$) in my .Rmd documents. The problem is that if a result is transformed in the scientific notation, it just screws up the entire equation, which is not displayed correctly:
```{r}
bla = 123456789
bli = 2
```
$$
B = `r bli`
$$
$$
B = `r bla`
$$

You can redefine the inline hook so that numbers can be formatted using LaTeX notation:
knit_hooks$set(inline = function(x) {
if (is.numeric(x)) knitr:::format_sci(x, 'latex') else x
})
(Put this inside your Rmd document)

Related

How to create text paragraph for results in R?

I'm writing my results (both text and tables) and the process is quite time-consuming...
I was wondering if a function in R could help me paste my results into the text so I could copy it into WORD?
For example:
R square = put number here, B = put number here... The difference between the models was significant/nonsignificant with p < put number here
Then I would love to paste it into WORD.
Best regards,
Daniel
Couldn't find any function that would help me... Tried Flextable...
If I understand the question correctly, this can largely be done in base R and reported with R Markdown or Quarto. You can either write the document as a .qmd or .rmd file and export to word, or simply render in RStudio and then copy and paste as you like.
I work the following way:
First assign the models to variables using <-.
Then examine the structure of the model with str().
In the text of the document, use $ with the variable name to access the various parts. Or paste it in the console for cut and paste of the values.
You may want to round() some numbers. Additionally, the function scales::pvalue() is very helpful for p values.
library(scales)
# Generate some model and assign it to a variable
model <- cor.test(cars$speed, cars$dist)
# Examine the structure of the model object
str(model)
Then in the text of an R markdown or Quarto document you can write:
$r$(`r model$parameter`) = `r round(model$estimate, digits = 2)`, $p$= `r pvalue(model$p.value, accuracy = 0.05)`
This will give the following: r(48) = 0.81, p= <0.05
In a code chunk $ is used to access a component. In text $ is used to start an equation. That can be confusing. To access a piece of R code in R Markdown text, use the convention `r <function or variable>` as in `r model$parameter` above. Alternatively, you can simply paste model$parameter into the console and copy the results to your target document.
You could knit the document to word, here's a quick example using inline R:
---
title: "test.Rmd"
output: word_document
---
``` {r, echo = FALSE}
# some variables
a <- 24
b <- 100
```
R square = `r a`, B = `r b` ... The difference between the models was `r if (a == 24) {"significant"} else {"insignificant"}` with p < `r b - a`

How to generate rmarkdown chunk within a chunk

I'm trying to generate a rmarkdown chunk using code. I've read similar questions and their solutions, such as using pander or using cat. I just can't seem to generate it. I also tried knitting the output manually. Here's an example of a Rmd file:
---
title: "test"
output: pdf_document
---
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}",
"2+2",
"```")
pander::pander(txt)
```
When I knit this, I get a verbatim {r} 2+2. I would like to see the number four instead. In my real example, I'm using bookdown and trying to generate a block2 chunk.
Any ideas how to generate this chunk that gets evaluated as R code?
Does this do what you want?
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}",
2+2,
"```")
pander::pander(txt)
```
This evalutates to
```{r} 4 ```
in your markdown document.
You using a string literal "2+2" as opposed to the expression 2+2. This is the first issue, I guess.
If you want it correctly parsed you need to add an sep = "\n" argument to paste or manually add the newline breaks.
I.e.
## R Markdown
```{r, results='asis',echo=FALSE}
txt <- paste("```{r}\n",
2+2,
"\n```", sep = "")
pander::pander(txt)
```
This evalutates to
```{r}
4
```
which is interpreted as R code in the markdown document.

How to show formatted R output with results='asis' in rmarkdown

Is there a way of showing formatter R output in rmarkdown/knitr when using results = 'asis'?
An example would be the following function:
myfun <- function() {
cat("hello!\n")
cat(c("one" = 1, "two" = 2))
}
Then, this chunk will print the second cat on a new row:
```{r}
myfun()
```
But this will ignore the formatting from myfun:
```{r, results = "asis"}
myfun()
```
Is there a way of keeping results='asis' but at the same time keep the output of myfun formatted as intended?
You can use the knitr chunk option results = "asis" if you are happy to add two or more spaces at the end of the line. That is, instead of "hello\n", you need to write "hello \n" to trigger the line break.
Example R Markdown code:
---
output: html_document
---
```{r}
myfun <- function() {
cat("hello! \n")
cat(c("one" = 1, "two" = 2))
}
```
```{r results = "asis"}
myfun()
```
Gives
Why the blank spaces? It's because two spaces at the end of a line are used to indicate a hard line break in markdown. For example, this quote is taken from Pandoc's Markdown (which is the default markdown flavour R Markdown uses):
Paragraphs
A paragraph is one or more lines of text followed by one or more blank lines. Newlines are treated as spaces, so you can reflow your paragraphs as you like. If you need a hard line break, put two or more spaces at the end of a line.

R Markdown embedding a function into a simple table

I'm new to R and I'm really liking the flexibility of R Markdown to create reports.
My problem is that I want to use a random number generating function I've created my tables. I want simple tables to include string headers and the following function:
> ran<-function(x){
+ x<-runif(n=1, min=13.5,max=15.5)
+ round(x, digits=2)}.
It won't allow me to create a table using this method?
```{r}
String |String |String
-------|------|------
ran(x)|ran(x)|ran(x)
```
My ultimate goal is to create practice worksheets with simple statistics that will be different but within a bounded integer range - so I can ask follow-up questions with some idea of the mean, median etc.
Any help would be greatly appreciated.
Perhaps you should read up on both how to build working R code and how to code up Rmd files since your function doesn't work and there are a few places in the R Markdown docs that show how to do this:
---
output: html_document
---
```{r echo=FALSE}
ran <- function(x) {
runif(n=1, min=13.5, max=15.5) + round(x, digits=2)
}
```
One |Two |Three
-----------|-------------|-----------
`r ran(2)` | `r ran(3)` | `r ran(4)`
`r ran(2)` | `r ran(3)` | `r ran(4)`
`r ran(2)` | `r ran(3)` | `r ran(4)`
`r ran(2)` | `r ran(3)` | `r ran(4)`
generates:
Also, neither SO nor RStudio charges extra for spaces in code blocks. It'd be good to show students good code style while you're layin' down stats tracks.
Here is an approach that automates much of the report generation and reduces the amount of code you need to type. For starters, you can turn this into a parameterized report, which would make it easier to create worksheets using different values of x. Here's an example:
In your rmarkdown document you would declare parameters x and n in the yaml header. n is the number of random values you want to produce for each value of x. The x and n values in the yaml header are just the defaults knitr uses if no other values are input when you render the report:
---
output: html_document
params:
x: !r c(1,5,10)
n: 10
---
Then, in the same rmarkdown document you would have the text and code for your worksheet. You access the parameters x and n with params$x and params$n, respectively.
For example, the rest of the rmarkdown document could look like the code below. We put x into a list called x_vals with named elements, so that the resulting column names in the output will be the names of the list elements. We feed that list to sapply to get a column of n random values for each value of x. The whole sapply statement is wrapped in kable, which produces a table in rmarkdown format.
```{r, include=FALSE}
library(knitr)
```
```{r, echo=FALSE}
# Create a named list of the x values that we passed into this document
x_vals = as.list(setNames(params$x, paste0("x=", params$x)))
kable(sapply(x_vals, function(i) round(runif(params$n, 13.5, 15.5) + i, 2)))
```
You can now click the "knit" button and it will produce a table using the default parameter values:
If instead you want to use different values for x and/or n, open a separate R script file and type the following:
rmarkdown::render("Worksheet.Rmd",
params = list(x = c(2,4,6,8),
n = 5),
output_file="Worksheet.html")
In the code above, the render function compiles the rmarkdown document we just created, but with new x and n values, and saves the output to a file called Worksheet.html. (I've assumed that we've saved the rmarkdown document to a file called Worksheet.Rmd.) Here's what the output looks like:
You can also, of course, add parameters for the lower and upper limits of the runif function, rather than hard-coding them as 13.5 and 15.5.
If you want to create several worksheets, each with different x values, you can put render in a loop:
df = expand.grid(1:3,5:6,10:11)
for (i in 1:nrow(df)) {
rmarkdown::render("Worksheet.Rmd",
params = list(x=unlist(df[i,]), n=10),
output_file=paste0(paste(unlist(df[i,]),collapse="_"),".html"))
}

If-Else Statement in knitr/Sweave using R variable as conditional

I am currently using knitr in R and RStudio to produce a LaTeX output. My code is a .Rnw file (called, say, testKnitr.Rnw) that is compiled to a pdf file with:
knit("testKnitr.Rnw") // in RStudio
pdflatex testKnitr.tex // in terminal
I would like to use an if-else syntax in LaTeX so that, depending on the value of an R variable, one of two LaTeX text paragraphs are output. In these LaTeX paragraphs, I would like to use expressions like \Sexpr{} and and \ref.
I have a minimal-working-example that is based on the second answer to a similar question posted here:
How to write an if-then statement in LaTeX using the value of an R variable in knitr/Sweave
Here is the MWE:
\documentclass{article}
\begin{document}
<<include=FALSE>>=
library(knitr)
opts_chunk$set(
concordance=TRUE
)
#
<<condition, include=FALSE, echo=FALSE>>=
x<- rnorm(1)
if(x>0){
text <- "This means x value of \Sexpr{x} was greater than 0"
}else{
text <- "This means x value of \Sexpr{x} was less than 0"
}
#
Testing the code:
<<print, results='asis', echo=FALSE>>=
cat(text)
#
\end{document}
Ideally, the intended output of the above MWE would a report with one line that contained something like:
"This means x value of 0.87 was greater than 0"
or
"This means x value of -0.87 was less than 0"
Before answering this question, I would like to take a look at the meta-question of whether this should be done.
Should we do it?
I don't think so. What we are basically doing here is using knitr to insert \Sexpr{x} in a document and then interpret \Sexpr{x}. There are no (obvious) reasons why we should take this detour instead of inserting the value of x directly to the document.
How to do it?
The following minimal example shows how it could be done anyways:
\documentclass{article}
\begin{document}
<<setup, echo = FALSE>>=
library(knitr)
knit_patterns$set(header.begin = NULL)
#
<<condition, echo=FALSE>>=
x <- rnorm(1)
if (x > 0) {
text <- "This means x value of \\Sexpr{x} was greater than 0"
} else {
text <- "This means x value of \\Sexpr{x} was less than 0"
}
#
Testing the code:
<<print, results='asis', echo=FALSE>>=
cat(text)
#
\end{document}
Two things are important here:
We need to escape the backslash in \Sexpr, resulting in \Sexpr.
We need to set knit_patterns$set(header.begin = NULL).
To compile the document:
Save it as doc.Rnw.
Then execute:
knitEnv <- new.env()
knit(input = "doc.Rnw", output = "intermediate.Rnw", envir = knitEnv)
knit2pdf(input = "intermediate.Rnw", output = "doc_final.tex", envir = knitEnv)
What happens?
The first call of knit generates intermediate.Rnw with the following content:
\documentclass{article}
\begin{document}
Testing the code:
This means x value of \Sexpr{x} was less than 0
\end{document}
You should note that knitr didn't include any definitions, commands etc. as usual to the LaTeX code. This is due to setting header.begin = NULL and documented here. We need this behavior because we want to knit the resulting document again in the second step and LaTeX doesn't like it when the same stuff is defined twice.
Creating the new environment knitEnv and setting it as envir is optional. If we skip this, the variable x will be created in the global environment.
In the second step we use knit2pdf to knit intermediate.Rnw and immediately generate a PDF afterwards. If envir was used in the first step, we need to use it here too. This is how x and it's value are conveyed from the first to the second knitting step.
This time all the gory LaTeX stuff is included and we get doc_final.tex with:
\documentclass{article}\usepackage[]{graphicx}\usepackage[]{color}
%% maxwidth is the original width if it is less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
\ifdim\Gin#nat#width>\linewidth
\linewidth
\else
\Gin#nat#width
\fi
}
\makeatother
%% more gory stuff %%
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\begin{document}
Testing the code:
This means x value of \ensuremath{-0.294859} was less than 0
\end{document}

Resources