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")
Related
It seems that stargazer tables cannot be referenced in RMarkdown anymore.
I have unsuccessfully tried to implement the workarounds posted on the github page that refer to this problem https://github.com/rstudio/bookdown/issues/175
---
title: "Ref Stargazer Test"
output:
bookdown::html_document2: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r results='asis'}
m1 <- lm(mpg ~ cyl + disp, mtcars)
stargazer::stargazer(m1, type = "html", label = "tab:model")
```
Table \#ref(tab:model) should show something on cars.
```{r mytab, results="asis"}
stargazer::stargazer(attitude,
type=ifelse(knitr::is_latex_output(),"latex","html"),
label=knitr::opts_current$get("label"),
title="Stargazer <3 Bookdown")
```
As Table \#ref(tab:mytab) shows, relationships may be hard work but love finds a way.
The referencing does not work as of July 2021 (rmarkdown 2.9, bookdown 0.22, stargazer 5.2.2).
Is there another workaround that works?
I don't know how to achieve this with stargazer. I will note that bookdown cross-references are a pretty recent feature, and that stargazer has not been updated in over 3 years, so issues are bound to arise.
One more modern alternative is the modelsummary package (disclaimer: I am the maintainer). In my biased opinion, this package is more flexible and robust, but YMMV.
Below I paste a minimal example of Rmarkdown document with cross-references. A couple things to note:
modelsummary detects the output format automatically, so you only need to specify LaTeX or HTML in the YAML header at the very top of your Rmarkdown document. No need to use the output argument of modelsummary (but check out the documentation anyway!).
The table label is set by the name of the chunk. Here, it is called "model", so we use tab:model as a cross-reference.
Your table needs a title, otherwise cross-references won't show up consistently.
---
title: "modelsummary cross-reference test"
output:
bookdown::html_document2: default
---
```{r model}
library(modelsummary)
m1 <- lm(mpg ~ cyl + disp, mtcars)
modelsummary(m1, title = "A table title")
```
Table \#ref(tab:model) should show something on cars.
I have found a solution myself that works for LaTeX and HTML.
---
title: "Ref Stargazer Test"
output:
bookdown::html_document2: default
---
Table \#ref(tab:mytable) is the referenced table.
```{r mytable, results='asis', fig.cap="This is my table."}
m1 <- lm(mpg ~ cyl + disp, mtcars)
# Use title caption from fig.cap
tit <- knitr::opts_current$get("fig.cap")
# Adding caption for html output
tit_html <- paste0('<span id="tab:',
knitr::opts_current$get("label"),
'">(#tab:',
knitr::opts_current$get("label"),
')</span>',
tit)
stargazer::stargazer(m1,
label = paste0("tab:", knitr::opts_current$get("label")),
title = ifelse(knitr::is_latex_output(), tit, tit_html),
type = ifelse(knitr::is_latex_output(),"latex","html"),
header = F
)
```
You can now also use the fig.cap argument in the chunk header to write the title you want to have for your table. For referencing, you have to refer to the chunk label (in this case "mytable"). The title argument in stargazer creates the <caption> element, this is why the html title is inserted there.
A simple way of solving this is by adding manually your table's name on stargazer.
label = "tab:table4"
So your code should look something like this:
stargazer(m1, label = "tab:mytable")
And now you will be able to cross reference as usual in Rmarkdown \ref{tab:mytable}
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`$"
I am producing a rmarkdown document, knitting to PDF and have a figure (figure 1) and a table (table 1) where the table explains the figure in more detail. I have no issue giving either of them a standard caption but I would like to change the table caption to be "Explanation of Figure 1". Is there any way of doing this?
The code chunks are listed below, please let me know if I need to provide more information:
YAML:
- \usepackage{caption} #and several others
output:
bookdown::pdf_document2:
keep_tex: no
latex_engine: xelatex
Code Chunks:
Figure 1:
```{r figure-1, fig.cap="Figure"}
ggplot()
```
Table 1:
```{r table, fig.cap="Explanation of Figure \#ref(fig:figure-1)"}
knitr
kableExtra::kable(caption = "Explanation of Figure \#ref(fig:figure-1)")
```
The main error message with one backslash is "Error: '#' is an unrecognized escape in character string" and suggests I forgot to quote character options, which is not true.
With two backslashes the document knits but produces the caption "Explanation of Figure reffig:table"
3 backslashes: the same error as with 1.
4 backslashes: the error is "pandoc-citeproc: reference ref not found. ! Package caption Error: \caption outside float."
Appreciate any suggestions!
Just a workaround, but may helps.
The \\#ref(fig:xxx) option works well when knitting to a html_document2.
To me pdf - creation worked fine when using pandoc in the terminal.
E.g.:
---
title: "Cross ref"
output:
bookdown::html_document2:
collapsed: no
theme: readable
toc: yes
link-citations: yes
---
```{r firstplot, fig.cap = "A plot with points." }
library(ggplot2)
plot_A = ggplot(data = data.frame(x = c(1:10),
y = seq(3, 8, length.out = 10)),
aes(x = x, y =y))+
geom_point()
plot_A
```
Now a second plot with a reference to Fig.: \#ref(fig:firstplot).
```{r secondplot, fig.cap = "This is the same as Fig.: \\#ref(fig:firstplot)
but now with a red line." }
library(ggplot2)
plot_A + geom_line(alpha = .75,col = "red")
```
after knitting just move to the folder containing the html and using pandoc
pandoc mini_ex-crossref.html -o mini_ex.pdf
I tried many different approaches text references, chunk captions, caption argument in the kable function and I´m sure there is a clever solution somewhere, so here is just a workaround with pure Latex.
Add a latex chunk with a label before the chunk with the figure:
```{=latex}
\begin{figure}
\caption{Figure 1}
\label{Fig-1}
```
```{r figure-1, echo = FALSE}
ggplot(mtcars) +
geom_point(aes(cyl, gear))
```
```{=latex}
\end{figure}
```
Now you can refer to Fig-1 in your latex-caption for the table with normal latex code \ref{Fig-1}:
```{=latex}
\begin{table}
\caption{Explanation of Figure \ref{Fig-1}}
```
```{r table}
kableExtra::kable(x = mtcars)
```
```{=latex}
\end{table}
```
Notes:
* In my opinion this is just a workaround.
* It´s not possible to use the chunk option fig.cap = "" and the latex code in parallel
J_F referenced Yihui Xie's excellent explanation of using text references in RMarkdown (https://bookdown.org/yihui/bookdown/markdown-extensions-by-bookdown.html#text-references), which you can use for figure and table captions that require more complicated things than plain text (e.g., formatting, cross-references, etc.). This may be a more flexible solution overall than remembering to escape the backslash in Robert's answer, and does not require a workaround with LaTeX.
As Yihui explains, all you need to do is define a text reference on a single line in markdown and reference that in the chunk option "fig.cap" or the "caption" parameter in knitr::kable(). Just be careful to make sure that each text reference is one paragraph that does not end in a white space.
Here's a basic example.
---
title: "Cross-referencing figures and tables within captions."
output: bookdown::pdf_document2
editor_options:
chunk_output_type: console
---
```{r load-packages}
library(knitr)
library(flextable)
```
(ref:first-fig-caption) Here's a complicated figure caption for the first figure, which can include complicated text styling like $m^2$ and references to other elements in the document, like Table \#ref(tab:mtcars) or Fig. \#ref(fig:cars).
```{r pressure, fig.cap = '(ref:first-fig-caption)'}
plot(pressure)
```
(ref:second-fig-caption) Here's a second complicated figure caption, also referencing Table \#ref(tab:mtcars).
```{r cars, fig.cap = '(ref:second-fig-caption)'}
plot(cars)
```
(ref:caption-table1) A caption for the first table. Check out this cross reference to Fig. \#ref(fig:pressure).
```{r mtcars}
mtcars |>
head() |>
kable(caption = '(ref:caption-table1)')
```
Using the following R script:
X = 2:10
summary(X)
I want to output only the results of the summary(X) command and omit the X = 2:10 part in my output in my LaTeX builder.
I've been trying for a few hours now using many different websites, but none of them seem to be working as intended.
Can anybody explain to me what I should include in both my R script and also my LaTeX input to make it work?
See the help page ?RweaveLatex; you're interested in
<<chunkid, echo = FALSE>>=
X = 2:10
summary(X)
#
In R Markdown, this works for me:
---
title: "Your latex"
author: "yourself"
date: "6/9/2018"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# your paper intro:
```{r, echo = TRUE, include = TRUE}
X = 2:10
summary(X)
```
I am want to print the output of a linear mixed model and the texts wraps.
Is there option that gets around this problem?
I have tried option(width=1000) and tidy=TRUE,tidy.opts=list(width.cutoff=600) to no avail.
EDIT:
Here is a minimum reproducible example.
---
title: "Untitled"
author: "NickHayden"
date: "5/8/2018"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(ggplot2)
library(lmerTest)
library(lme4)
library(tidyverse)
```
## R Markdown
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r cars}
df <- sample_n(diamonds, size = 100)
df <- df %>% mutate(randoms = rep(c("A","B", "C"), length.out = 100))
mod <- lmer(price ~ factor(color) * factor(clarity) * factor(cut) + (1|randoms), data = df)
print(summary(mod))
```
Here the text should wrap around the window and lines may wrap under as well.
An anternative is to export the output to a text file. The following link shows how to achieve this.
Export R output to a file
Example:
test <- c("asb", "asb", "asb", "abc")
out <- capture.output(summary(test))
cat("My title", out, file="example_output.txt", sep="\n", append=TRUE)