Refer variable to LATEX function - r

Hi I am writing an R Markdown document in which there is a Latex function. I would like to refer the variable in the LATEX to the variable in the R code so that it automatically update the LATEX if the R code generates a new results for the variable.
Rcode:
var = rnorm(1,0)
Latex part:
$$ f(x) = beta_{0}*var $$
I have already looked these links but they doesn't work for me.
https://github.com/yihui/knitr/blob/master/inst/examples/knitr-minimal.Rmd;
Is there an R Markdown equivalent to \Sexpr{} in Sweave?; https://tex.stackexchange.com/questions/362119/passing-variable-from-r-to-latex

You can do
```{r, echo=FALSE, results='asis'}
var <- rnorm(1)
cat(sprintf("$$f(x) = \\beta_0*%s$$", var))
```

I believe this question has been answered in the post Is there an R Markdown equivalent to \Sexpr{} in Sweave? You can use inline R expressions `r `, e.g.
$$f(x) = \beta_{0} + `r var` * \beta_{1} + `r var2` * \beta_{2} + e$$
where var and var2, etc. are your variables in R.

Related

Inline text in Markdown - adding results from code

I have been told that I can write a results section for a paper on Markdown. So say I want to get the value Robust_t_time_1 which I have derived in my R code section:
```{r fig.width=4, fig.height=4, echo=FALSE, message=FALSE,
warning=FALSE, include = TRUE}
coefs.robust <- data.frame(coef(summary(model_robust)))
t_values.robust1 <- coefs.robust$t.value
Robust_t_time_1 <- t_values.robust1[3]
Robust_t_time_1
```
And I am writing in the text section of Markdown and I want to quote this value. How do I refer to it? I have been trying t = {r} Robust_t_time_1 . This does not work. I know it should be possible.
To evaluate the value you have to use back ticks in the text: "t = `r Robust_t_time_1`"
You can also render it as an inline equation in the text by using dollar signs: "$t = `r Robust_t_time_1`$"

How to output values of R variables in an inline LateX equation in R Markdown (i.e. dynamically updated)

I am unable to find a way to implement r code into an inline LateX equation in R markdown. The goal is to not have to hard code the values of my variable 'values' if they were to change.
Given:
values <- c(1.4, 2.5, 7, 9)
avg <- sum(values)/length(values)
avg
My current approach was to just copy and paste the values of my R variable into the LaTeX inline equation as such:
The average of $values$ is $\hat{v} = \frac{1.4 + 2.5 + 7 + 9}{4} = 4.975$
But this is cumbersome even with such a trivial example.
Using inline r code with r values[1] does not work inside of a LateX equation in R Markdown.
---
title: Inline LaTeX using \textsf{\textbf{R}} variables
output: pdf_document
---
```{r, echo=FALSE}
# set variables
set.seed(1)
values <- sample(10:100, sample(3:5))/10
lv <- length(values)
avg <- sum(values)/lv
```
\begin{center}
The average of $values$ is
$\hat{v} = \frac{`r paste(values, collapse=" + ")`}{`r lv`} = `r round(avg, 3)`$.
\end{center}
If you same that as a .rmd file and render it you should get something like

knitr markdown not displaying basic plot in r

I am trying to print a simple plot with knitr markdown.
below is my code.
```{Simple plot}
library(datasets)
with(airquality, plot(Wind, Ozone))
```
If I run this in r code file, it returns the plot properly.
However, when running this in a markdown file, it only shows code but no plot to the printed document.
what am I doing wrong?
Use ```{r} where r means R langage :
```{r}
library(datasets)
with(airquality, plot(Wind, Ozone))
```

P-values significance not showed in stargazer html regression table

I am having trouble with the Notes significance (asterisks) not appearing when using stargazer to format html tables. The result is ok when using latex.
Here is my source file "teste.Rmd"
---
title: "Untitled"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r data}
#some data
set.seed(123)
X = rnorm(500,10,3)
Y = 10+ 3*I(X^1.2) + rnorm(500)
# models
m1 = lm(Y~X)
m2 = lm(Y~X+I(X^2))
```
```{r res,warning=FALSE,message=FALSE,results='asis'}
library(stargazer)
stargazer(m1,m2,type = 'html',title = 'Models' )
```
The result is below
The same with latex produces this
As you can see the asterisks in Notes are formatted correctly with latex but not with html option. How to get the same behavior with html?
Maybe it is a bug as #jaySf said in the comments to the original question. But based on #tmfmnk's answer and htmltools package I ended with a workaround. This is the updated relevant part of the source file.
```{r res,warning=FALSE,message=FALSE,results='hide'}
library(stargazer)
stargazer(m1,m2,type = 'html',title = 'Models', out = "table1.html")
```
```{r, echo=FALSE}
htmltools::includeHTML("table1.html")
```
Now I got the desired result
Try adding customized notes using notes and notes.append parameters as follows:
stargazer(m1,m2,type='html',notes="<span>***</span>: p<0.01; <span>**</span>: p<0.05; <span>*</span>: p<0.1",notes.append=F)
I originally thought that using backslash to escape * will work, e.g. notes="\\*\\*\\*: p<0.01; \\*\\*: p<0.05; \\*: p<0.1". Unfortunately, it doesn't. I also tried to use the HTML code of *, i.e. *, e.g. notes="***: p<0.01; **: p<0.05; *: p<0.1". Still it doesn't work.
However, surrounding * with an HTML tag works. It doesn't have to be <span></span>. I tried <b></b>, etc. and they worked.
When exported through out it is working fine:
stargazer(m1,m2,type = 'html',
title = 'Models',
out = "/path/table.html")

Dynamic references to figures in a R comment within Sweave document

I would like to find a way to use the LaTeX \ref{} markup to comment in the R code within a Sweave .Rnw file. Here are two examples, one in print
http://cm.bell-labs.com/cm/ms/departments/sia/project/nlme/UGuide.pdf
and one to use to work with:
The .Rnw file
% File: example.Rnw
\documentclass{article}
\usepackage{fullpage}
\usepackage{graphics}
\usepackage{Sweave}
\usepackage[margin = 10pt, font=small, labelfont={bf}]{caption}
\begin{document}
Here is an example file to show what I want to do. I would like to figure out how to use the \LaTeX\ reference command to reference a figure being generated by R code. Note in the R code, in a comment there is a reference to the figure, but of course the output file shows a verbatim copy of the \LaTeX\ markup. Does anyone know how to get something for Figure \ref{fig2}?
<< example plot >>=
library(reshape)
library(ggplot2)
n <- 100
lambda <- 1 / 3
x <- seq(0, qexp(0.999, rate = lambda), length = n)
q1.a <- data.frame(x = x,
f = dexp(x, rate = lambda),
F = pexp(x, rate = lambda))
q1.a <- melt(q1.a, id.vars = 'x')
g <- ggplot(q1.a) + # Produces \ref{fig1}
aes(x = x, y = value) +
geom_line() +
facet_wrap( ~ variable, scale = "free_y")
ggsave(g, filename = "example1.jpeg")
#
\begin{figure}[h]
\centering
\includegraphics[width = 0.48\textwidth]{./example1}
\caption{Exponential Distribution based plots.}
\label{fig1}
\end{figure}
Here is more of what I would like to see:
<< example plot 2 >>=
ggsave(g + geom_point(), filename = "example2.jpeg") # Produces Figure 2
#
\begin{figure}
\centering
\includegraphics[width = 0.48\textwidth]{./example2}
\caption{Exponential Distribution based plots with points and lines.}
\label{fig2}
\end{figure}
\end{document}
and the pdf is build with the R commands
Sweave(file = 'example.Rnw',
engine = "R",
keep.source = 'TRUE',
echo = 'TRUE',
results = 'verbatim')
tools::texi2dvi(file = "example.tex",
pdf = TRUE,
clean = TRUE)
Any insight on how do this would be great.
Here is one way to solve this issue by redefining the Sinput environment in which source code is wrapped by Sweave. By default, it is a simple verbatim environment which is not processed by latex for tokens. The trick is to redefine it to use the alltt environment which allows some tokens to be parsed inside the alltt environment. Note that this might lead to unwanted side effects that I am not aware of, so use with caution!
Here is a reproducible example that works. If you compile it, you will generate a file where ref{fig1} is replaced by the figure number.
\documentclass{article}
\usepackage{Sweave}
\usepackage{alltt}
\renewenvironment{Sinput}{\begin{alltt}}{\end{alltt}}
\begin{document}
In this document, we will create a plot using `R`, and reference its position in
the source code.
<<produce-plot, results = hide>>=
pdf('example1.pdf')
plot(1:10, 1:10) # Produces Figure \ref{fig1}
dev.off()
#
\begin{figure}
\includegraphics{example1.pdf}
\caption{Figure 1}
\label{fig1}
\end{figure}
\end{document}

Resources