The knitr::kable with the latex format option produces a tabular environment.
For example,
# produces a tabular environment
knitr::kable(head(cars),
format = 'latex')
produces
\begin{tabular}{r|r}
\hline
speed & dist\\
\hline
4 & 2\\
\hline
4 & 10\\
\hline
7 & 4\\
\hline
7 & 22\\
\hline
8 & 16\\
\hline
9 & 10\\
\hline
\end{tabular}
The table is not centered. If I use kable_stylying from kableExtra, whose value for the option position defaults to center, I get a centered floating table, using the LaTeX table enviornment.
For example, this
# produces a tabular environment inside a table
knitr::kable(head(cars),
format = 'latex') %>%
kableExtra::kable_styling()
produces
\begin{table}
\centering
\begin{tabular}{r|r}
\hline
speed & dist\\
\hline
4 & 2\\
\hline
4 & 10\\
\hline
7 & 4\\
\hline
7 & 22\\
\hline
8 & 16\\
\hline
9 & 10\\
\hline
\end{tabular}
\end{table}
However, I just want to make a small, almost inline, table. I do not want it to float. I do not want captions, etc. What I want then is something to produce LaTeX code like this:
\begin{center}
\begin{tabular}{r|r}
\hline
speed & dist\\
\hline
4 & 2\\
\hline
4 & 10\\
\hline
7 & 4\\
\hline
7 & 22\\
\hline
8 & 16\\
\hline
9 & 10\\
\hline
\end{tabular}
\end{center}
Is that possible using knitr and kableExtra?
I can use a workaround. For example, use chunk options results='asis', and in the chunk, do
cat("\\begin{center}",sep='\n')
knitr::kable(head(cars),
format = 'latex')
cat("\\end{center}",sep='\n')
However, I would like to know if this it is possible without the workaround and whether I am missing something.
Minimal reproducible example
The following is a minimal working example of an RMarkdown document at produces the three kinds of tables mentioned above. Dependencies are magrittr, knitr, and kableExtra.
---
output: pdf_document
---
```{r}
library(magrittr)
```
This produces a `tabular`, non-floating, table. But it is not centered.
```{r}
knitr::kable(head(cars), format = 'latex')
```
The following code produces a centered table, but using a `table` environment, so it floats (in this case to the top of the page), which is probably what we usually want, but we don't *always* want.
```{r}
knitr::kable(head(PlantGrowth), format = 'latex') %>%
kableExtra::kable_styling()
```
We can produce a centered `tabular` environment using chunk option `results='asis'` etc.
```{r, echo=FALSE, results='asis'}
cat("\\begin{center}",sep='\n')
knitr::kable(head(ToothGrowth),
format = 'latex')
cat("\\end{center}",sep='\n')
```
Rendering this (as a pdf_document) creates a single page pdf with this content:
You just need to set the table.envir argument to "center" to wrap the \tabular in \begin{center} ... \end{center}. In your MRE:
---
output: pdf_document
---
```{r}
library(magrittr)
```
This produces a `tabular`, non-floating, table, and it *is* centered:
```{r}
knitr::kable(head(cars), format = 'latex', table.envir = "center")
```
If you want to wrap it twice (e.g. centered and boldface), you can use something like table.envir = c("bf", "center", "bf"): because kable() isn't smart enough to reverse the order when adding the \end{} markers, you need to use a palindrome.
If you use \centering, you'll avoid the extra vertical spacing from the center environment:
---
output:
pdf_document:
keep_tex: true
header-includes:
- \AddToHook{env/tabular/before}{\begingroup\centering}
- \AddToHook{env/tabular/after}{\par\endgroup}
---
```{r}
library(magrittr)
```
text
```{r}
knitr::kable(head(cars), format = 'latex')
```
text
Related
I am trying to output a LaTex file using Stata's esttab command. I cannot get the decimals to align, nor can I get the nice formatting from the "booktabs" option to work. I also would like to increase the width of the columns. I have been tinkering with this for hours and have had no luck. Below is my Stata code and the LaTex code that I am running through Overleaf. Any help would be greatly appreciated!
Here is my Stata code:
#delimit ;
esttab r1 r2 r3 r4 using "C:\Users\user\Dropbox\Private
Code\Code\STATA\latex\table1.tex", replace
b(3) nomtitle label star(* 0.10 ** 0.05 *** 0.01)
booktabs alignment(D{.}{.}{-1})
title(Placeholder)
s(N DAY FFE FIRM_QUARTER r2_a,
fmt(%9.0fc 0 0 0 3)
label("Observations" "Day FE" "Firm FE" "Firm-Quarter FE" "Adj. R-Sq{\super 2}"))
compress nocons;
Here is the LaTex code it spits out:
\begin{table}[htbp]\centering
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
\caption{Placeholder}
\begin{tabular}{l*{4}{D{.}{.}{-1}}}
\toprule
&\multicolumn{1}{c}{(1)} &\multicolumn{1}{c}{(2)} &\multicolumn{1}
{c}{(3)} &\multicolumn{1}{c}{(4)} \\
\midrule
VAR1 & 0.007\sym{***}& 0.007\sym{***}& 0.006\sym{***}& 0.007\sym{***}\\
& (8.55) & (7.82) & (7.67) & (8.54) \\
\addlinespace
VAR2 & 0.132\sym{***}& 0.131\sym{***}& 0.131\sym{***}& 0.132\sym{***}\\
& (20.35) & (20.15) & (20.15) & (20.35) \\
\midrule
Observations &1,315,077 &1,315,077 &1,315,077 &1,315,077
\\
Day FE & No & Yes & Yes & No \\
Firm FE & Yes & No & Yes & No \\
Firm-Quarter FE & No & No & No & Yes \\
Adj. R-Sq{\super 2}& 0.045 & 0.027 & 0.046 & 0.044
\\
\bottomrule
\multicolumn{5}{l}{\footnotesize \textit{t} statistics in parentheses}\\
\multicolumn{5}{l}{\footnotesize \sym{*} \(p<0.10\), \sym{**} \(p<0.05\), \sym{***} \(
p<0.01\)}\\
\end{tabular}
\end{table}
Since you haven't provided the full code, I can't see what would your output be. When I add \documentclass{article} with missing packages in a preamble, I get very wide table which does not fit a page. Also, I don't know whether the code is automatically generated or created/altered by you.
Assuming the latter, I would do the following. Since you add footnotes in the table, I would enclose tabular within threeparttable, which splits the area for table into three parts: top for captions, middle for a table definition e.g. tabular, and bottom part for footnotes. It also adds a convenient macro \tnote{}.
Secondly, dcolumn causes big numbers to be pushed way too much to the left. You should let dcolumn suppress their alignment. I personally don't know how, although I assume there is a way.
I prefer siunitx for formatting numbers in tables. However siunitx needs a bit more work. It automatically parses numbers in cells and any non-number content generates errors. Therefore, non-numbers need to be enclosed within {...} which instructs siunitx to leave the content intact. It also forces numbers not to be formatted, aligned etc., which is what I did for the big numbers you have in the table. There's also option to format thousands and millions with any separator of your choice. For instance you could use one of the macros: \,, :, or \; for thin, mid or thick space, respectively instead of ,.
Below is my suggestion for your table based on siunitx and threeparttable, so you can compare it with your approach.
\documentclass{article}
\usepackage{array}
\usepackage{booktabs}
\usepackage{siunitx}
\usepackage{threeparttable}
\newcommand\super[1]{\textsuperscript{#1}}
\sisetup{
group-separator={,},
table-format=1.3,
table-align-text-after = false,
}
\begin{document}
\begin{table}[htbp]
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
\centering
\begin{threeparttable}
\caption{Placeholder}
\begin{tabular}{l *{4}{S}}
\toprule
& \multicolumn{1}{c}{(1)}
& \multicolumn{1}{c}{(2)}
& \multicolumn{1}{c}{(3)}
& \multicolumn{1}{c}{(4)} \\
\midrule
{VAR1} & 0.007\tnote{***} & 0.007\tnote{***} & 0.006\tnote{***} & 0.007\tnote{***} \\
& {(8.55)} & {(7.82)} & {(7.67)} & {(8.54)} \\
\addlinespace
VAR2 & 0.132\tnote{***} & 0.131\tnote{***} & 0.131\tnote{***} & 0.132\tnote{***} \\
& {(20.35)} & {(20.15)} & {(20.15)} & {(20.35)} \\
\midrule
Observations
& \multicolumn{1}{c}{\num{1315077}}
& \multicolumn{1}{c}{\num{1315077}}
& \multicolumn{1}{c}{\num{1315077}}
& \multicolumn{1}{c}{\num{1315077}} \\
Day FE & {No} & {Yes} & {Yes} & {No} \\
Firm FE & {Yes} & {No} & {Yes} & {No} \\
Firm-Quarter FE & {No} & {No} & {No} & {Yes} \\
Adj. R-Sq{\super2} & 0.045 & 0.027 & 0.046 & 0.044 \\
\bottomrule
\end{tabular}
\par\(t\) statistics in parentheses
\par\tnote{*} \(p < 0.10\),\quad\tnote{**} \(p < 0.05\),\quad\tnote{***} \(p < 0.01\)
\end{threeparttable}
\end{table}
\end{document}
EDIT. I also enclosed statistics in{...} because siunitx does not recognised brackets as part of a number.
I want to put a table and figure above/below one another in my article tex file as they are related. Until now it has worked in this document but suddenly it isn't working and I can't compile in Overleaf. Please help.
\begin{document}
\begin{minipage}[b]{1\textwidth}
\centering
\captionof{table}{Best Case Scenario A IC values when synthesis, desiccation (and algae collection) have been excluded from the system.}
\label{tab:BestA_synthANDdesiccation_excluded}
\begin{tabular}{#{}llcc#{}}
\toprule
IC & Unit & Total (no collection) & Total (with collection) \\ \midrule
CC & kg CO2 eq & -1.1E+03 & -7.0E+02 \\
Ecotox & CTUe & 2.1E+02 & 1.4E+04 \\
HTnc & CTUh & 6.9E-08 & 1.4E-05 \\
PM & disease inc. & 3.7E-07 & 1.0E-05 \\
RUf & MJ & 9.3E+01 & 5.6E+03 \\
RUm & kg Sb eq & 8.0E-06 & 3.6E-02 \\ \bottomrule
\end{tabular}
\end{minipage}
\begin{minipage}
\includegraphics[width=1\textwidth]{Pictures/A_best_nosynANDnodesiccationANDnocollection.png}
\captionof{figure}{Characterisation of the sub-systems in best-case scenario A when synthesis, desiccation and algae collection have been excluded from the system boundaries. Method: EF 3.0 Method (adapted) V1.00}
\label{fig:Abest_nosyn_nodesiccation}
\end{minipage}
\end{document}
The main problem is that the minipage has an mandatory argument to specify the width, so you'll need
\begin{minipage}{\linewidth}
Some other comments:
best not specify a file type for your image \includegraphics[width=1\textwidth]{Pictures/A_best_nosynANDnodesiccationANDnocollection}. If you have the same image in different formats latex will then include the one best suited for the engine you use to compile your document
Unless your minipage is in a float environment like figure or table you want to add \noindent before the minipage. Without this there is not enough space in your line to fit a minipage with \textwidth
if you want to have the numbers in your table nicely aligned, have a look at the siunitx package
\documentclass{article}
\usepackage{caption}
\usepackage{booktabs}
\usepackage{graphicx}
\begin{document}
\noindent%
\begin{minipage}[b]{1\textwidth}
\centering
\captionof{table}{Best Case Scenario A IC values when synthesis, desiccation (and algae collection) have been excluded from the system.}
\label{tab:BestA_synthANDdesiccation_excluded}
\begin{tabular}{#{}llcc#{}}
\toprule
IC & Unit & Total (no collection) & Total (with collection) \\ \midrule
CC & kg CO2 eq & -1.1E+03 & -7.0E+02 \\
Ecotox & CTUe & 2.1E+02 & 1.4E+04 \\
HTnc & CTUh & 6.9E-08 & 1.4E-05 \\
PM & disease inc. & 3.7E-07 & 1.0E-05 \\
RUf & MJ & 9.3E+01 & 5.6E+03 \\
RUm & kg Sb eq & 8.0E-06 & 3.6E-02 \\ \bottomrule
\end{tabular}
\end{minipage}
\begin{minipage}{\linewidth}
\includegraphics[width=1\textwidth]{example-image-duck}
\captionof{figure}{Characterisation of the sub-systems in best-case scenario A when synthesis, desiccation and algae collection have been excluded from the system boundaries. Method: EF 3.0 Method (adapted) V1.00}
\label{fig:Abest_nosyn_nodesiccation}
\end{minipage}
\end{document}
How can I autonumber equations in an Rmarkdown document?
I've tried including "\usepackage{mathajax}" in the header, but the equations won't autonumber. I believe I need to configure mathjax, but can't figure out how.
I'm open to any solutions.
Please note, the solution in this post does not work.
Edit:
A simplified example of the desired output is below.
The code for the above image is below. I tried using \begin{equation} and \end{equation} instad of "align";however, the HTML document does not output the formulas correctly.
---
header-includes:
- \usepackage{amsmath}
output:
html_document: default
---
\begin{align}
2+2 = 4 \tag{1} \\
3+2 = 5 \tag{2} \\
4+2 = 6 \tag{3} \\
5+2=7 \tag{4} \\
\end{align}
You can get pretty close by using bookdown::html_document2, c.f. the documentation:
---
output:
bookdown::html_document2: default
---
\begin{align}
2+2 &= 4 \\
3+2 &= 5 (\#eq:three) \\
4+2 &= 6 (\#eq:four) \\
5+2 &= 7 (\#eq:five)
\end{align}
Result:
You get an equation number for every equation where you put a label. I have omitted the label on the first equation to show this effect. This is slightly different from the LaTeX's behavior, where you have to use \notag in an align environment to not get an equation number.
I am working with the community-contributed command outreg2 to export regression estimates from a logit model to LaTeX.
Is there a way to show the table reference/label, for example, "Table 1: Some Title"?
I cannot seem to be able to do this using outreg2:
logit v1 v2 v43, or
outreg2 using "table", label cti(odds ratio) eform tex replace ctitle(Logit)
With esttab, using \label in the title option to get the desired result works:
esttab using "Table.tex",tex eform label replace title("Logit"\label{tab1})
Any suggestions?
EDIT:
Note that even when i do the following:
outreg2 using "table", label cti(odds ratio) eform tex replace ///
ctitle(Logit) title("Logit"\label{tab1})
This only produces the following:
Consider the following toy example:
webuse lbw
logit low age lwt i.race smoke ptl ht ui, or
Both esttab and outreg2 produce the same result when their title() option is used:
esttab, tex eform label replace title("Logit"\label{tab1})
outreg2 using "table", tex label cti(odds ratio) eform replace title("Logit"\label{tab1})
However, this will not work when typesetting as outreg2 produces
different markup than esttab.
The way to do what you want with outreg2 is to run the following from Stata:
outreg2 using table, tex replace label cti(odds ratio) eform
Unlike esttab, the outreg2 command does not have an option to insert markup
directly from within Stata. Thus you will have to add the markup below manually:
.
.
.
\begin{table}[htbp]\centering
\caption{Logit \label{tab1}}
.
.
.
\end{table}
.
.
.
The produced tex file should then look as follows:
\documentclass[]{article}
\setlength{\pdfpagewidth}{8.5in} \setlength{\pdfpageheight}{11in}
\begin{document}
\begin{table}[htbp]\centering
\caption{Logit \label{tab1}}
\begin{tabular}{lc} \hline
& (1) \\
VARIABLES & odds ratio \\ \hline
& \\
birthweight<2500g & \\
& \\
age of mother & 0.973 \\
& (0.0355) \\
weight at last menstrual period & 0.985** \\
& (0.00682) \\
race = 2, black & 3.535** \\
& (1.861) \\
race = 3, other & 2.368** \\
& (1.040) \\
smoked during pregnancy & 2.518** \\
& (1.009) \\
premature labor history (count) & 1.719 \\
& (0.595) \\
has history of hypertension & 6.250*** \\
& (4.322) \\
presence, uterine irritability & 2.135* \\
& (0.981) \\
Constant & 1.586 \\
& (1.910) \\
& \\
Observations & 189 \\ \hline
\multicolumn{2}{c}{ seEform in parentheses} \\
\multicolumn{2}{c}{ *** p$<$0.01, ** p$<$0.05, * p$<$0.1} \\
\end{tabular}
\end{table}
\end{document}
Leaving this here for future reference.
Actually, if you add the option tex(fragment) to outreg2, the resulting file will only contain the tabular environment. Then, you can create the table environment, with the caption that you desire, and use \input only to replace the tabular environment.
I want to insert a \table in \enumerate environment and I have something like this:
\begin{enumerate}
\item Item 1.
\item Item 2.
\item \begin{table}[htbp]
\textbf{\caption{Table1 Caption}}
\centering
\begin{tabular}{c c}
\hline\hline
Value 1 & Value 2\\
\hline
r1c1 & r2c2\\
r2c1 & r2c2\\
r3c1 & r3c2\\
\hline
\end{tabular}
\label{table1}
\end{table}
\item \begin{table}[htbp]
\textbf{\caption{Table 2 Caption}}
\centering
\begin{tabular}{ccc}
\hline\hline
Value 1 & Value 2 & Value 3\\
\hline
r1c1 & r1c2 & r1c3\\
r2c1 & r2c2 & r2c3\\
r3c1 & r3c2 & r3c3\\
\end{tabular}
\label{table2}
\end{table}
\item \ref{table1} and \ref{table2}
\end{enumerate}
But when I compile the latex document the \enumerate number are no where near the table. Also when I refer to label "table1" and "table2" it shows up as 3 and 4 respectively (for extra info this part is in subsection 3.3 and these are the only two tables in the whole document).
How do I use \table environment with \enumerate environment. I have seen people use just \tabular with \enumerate but I want to use \table as it gives me an easy option to define \caption and \label.
Also regarding table labeling I am assuming it has something to do with subsection number but I can't really figure it out.
I would really appreciate any help regarding this matter.
A table environment is a float. It is not meant to be included in other environments.
You can use a tabular environment like this:
\documentclass[a4paper, 11pt]{article}
\begin{document}
\begin{enumerate}
\item Item 1.
\item Item 2.
\item \begin{tabular}[t]{c c}
Value 1 & Value 2\\
\hline
r1c1 & r2c2\\
r2c1 & r2c2\\
r3c1 & r3c2\\
\hline
\end{tabular}
\item \begin{tabular}[t]{ccc}
Value 1 & Value 2 & Value 3\\
\hline
r1c1 & r1c2 & r1c3\\
r2c1 & r2c2 & r2c3\\
r3c1 & r3c2 & r3c3\\
\end{tabular}
\end{enumerate}
\end{document}
The output will look like this:
Note that the vertical alignment will look weird if you try tp put \hline on top of the table.
Edit 1: You can put a \label almost everywhere you like, but it will not refer to itself as a "Table" unless a variable is set. You'd have to delve into the bowels of LaTeX to see how that is done.
There are at least two packages (capt-of and caption) that provide a \captionof command to define a caption outside a figure or table environment.