Jakob Jul Elben
Jakob Jul Elben

Reputation: 83

R markdown won't compile a piece of LaTeX code

I have the following piece of code, which I would like to run I R markdown. I have tried to run it in a LaTeX compiler, which works absolutely fine. But when I add it into R markdown it won't compile the piece of code.

---
title: "Titre"
date: Fecha
output:
 pdf_document:
  keep_tex: true
  includes:
   in_header: mystyle.sty


---



\begin{table}[!htbp] \centering 
  \caption{} 
  \label{} 
\begin{tabular}{@{\extracolsep{5pt}}lD{.}{.}{-3} } 
\\[-1.8ex]\hline 
\hline \\[-1.8ex] 
 & \multicolumn{1}{c}{\textit{Dependent variable:}} \\ 
\cline{2-2} 
\\[-1.8ex] & \multicolumn{1}{c}{mpg} \\ 
\hline \\[-1.8ex] 
 cyl & -2.876^{***} \\ 
  & (0.322) \\ 
  & \\ 
 Constant & 37.885^{***} \\ 
  & (2.074) \\ 
  & \\ 
    \hline \\[-1.8ex] 
Observations & \multicolumn{1}{c}{32} \\ 
R$^{2}$ & \multicolumn{1}{c}{0.726} \\ 
Adjusted R$^{2}$ & \multicolumn{1}{c}{0.717} \\ 
Residual Std. Error & \multicolumn{1}{c}{3.206 (df = 30)} \\ 
F Statistic & \multicolumn{1}{c}{79.561$^{***}$ (df = 1; 30)} \\ 
\hline 
\hline \\[-1.8ex] 
\textit{Note:}  & \multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\ 
\end{tabular} 
\end{table} 

The file mystyle.sty contains the following

\usepackage{dcolumn} 
\newcolumntype{d}[1]{D{.}{.}{#1}}    
\usepackage{booktabs}
\newcommand{\mc}[1]{\multicolumn{1}{c}{#1}} % handy shortcut macro
\usepackage{verbatim}

Are there someone who can explain why R markdown can't compile what's above?

Upvotes: 1

Views: 464

Answers (1)

Weihuang Wong
Weihuang Wong

Reputation: 13128

By adding the table code line by line and recompiling each time, I isolated the problem to the lines with carets, e.g. the line that reads cyl & -2.876^{***} \\.

I was able to compile the document by enclosing the superscripted part in two $ signs, i.e.

cyl & -2.876$$^{***}$$ \\

(I don't know why you need two, rather than just one, $.)

This compiles just fine:

---
title: "Titre"
date: Fecha
output:
 pdf_document:
  keep_tex: true
  includes:
   in_header: mystyle.sty
---

\begin{table}[!htbp] \centering 
\begin{tabular}{@{\extracolsep{5pt}}lD{.}{.}{-3} }
\\[-1.8ex]\hline 
\hline \\[-1.8ex] 
& \multicolumn{1}{c}{\textit{Dependent variable:}} \\ 
\cline{2-2} 
\\[-1.8ex] & \multicolumn{1}{c}{mpg} \\ 
\hline \\[-1.8ex] 
cyl & -2.876$$^{***}$$ \\
& (0.322) \\ 
& \\ 
Constant & 37.885$$^{***}$$ \\ 
& (2.074) \\ 
& \\ 
\hline \\[-1.8ex] 
Observations & \multicolumn{1}{c}{32} \\ 
R$^{2}$ & \multicolumn{1}{c}{0.726} \\ 
Adjusted R$^{2}$ & \multicolumn{1}{c}{0.717} \\ 
Residual Std. Error & \multicolumn{1}{c}{3.206 (df = 30)} \\ 
F Statistic & \multicolumn{1}{c}{79.561$^{***}$ (df = 1; 30)} \\ 
\hline
\hline \\[-1.8ex] 
\textit{Note:}  & \multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\
\end{tabular}
\end{table}

Upvotes: 2

Related Questions