How do I compile a LaTeX table exported from R? - latex

I'm completely new to LaTeX and have the MacTeX 2009 package installed, with the intent of having tables from R output into LaTeX and formatted as PDF.
I get the following LaTeX code (below) when I run an example in R (it renders ok in R, but I´d like to use TeXshop). However, when I paste this into a TeXshop window, I get the following error:
./Untitled.tex:2: LaTeX Error: Environment table undefined
I´m sure there is something very basic I´m missing here.
% latex.default(cstats, title = title, caption = caption, rowlabel = rowlabel,
% col.just = col.just, numeric.dollar = FALSE, insert.bottom = legend,
% rowname = lab, dcolumn = dcolumn, extracolheads = extracolheads,
% extracolsize = Nsize, ...)
%
\begin{table}[!tbp]
\caption{Descriptive Statistics by treatment\label{f}}
\begin{center}
\begin{tabular}{lccc}\hline\hline
\multicolumn{1}{l}{}&\multicolumn{1}{c}{Drug}&\multicolumn{1}{c}{Placebo}&\multicolumn{1}{c}{Test Statistic}\tabularnewline
&\multicolumn{1}{c}{{\scriptsize $N=263$}}&\multicolumn{1}{c}{{\scriptsize $N=237$}}&\tabularnewline
\hline
age&{\scriptsize 46.5~}{49.9 }{\scriptsize 53.2} &{\scriptsize 46.7~}{50.0 }{\scriptsize 53.4} &$ F_{1,498}=0.1 ,~ P=0.754 ^{1} $\tabularnewline
sex~:~m&47\%~{\scriptsize~(123)}&44\%~{\scriptsize~(104)}&$ \chi^{2}_{1}=0.42 ,~ P=0.517 ^{2} $\tabularnewline
Primary~Symptoms~:~Depressed&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Headache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Hangnail&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Muscle~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
~~~~Stomach~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$\tabularnewline
\hline
\end{tabular}
\end{center}
\noindent
{\scriptsize $a$\ }{$b$\ }{\scriptsize $c$\ } represent the lower quartile $a$,
the median $b$, and the upper quartile $c$\ for continuous variables.\\
Numbers after percents are frequencies.\\\indent Tests used:\\
\textsuperscript{\normalfont 1}Wilcoxon test; \textsuperscript{\normalfont 2}Pearson test
\end{table}

You need some boilerplate around this to set up the document -- the LaTeXTemplate in TexShop should do.
Your \begin{table} is commented out with a preceding %
There are some missing backslashes in the legend text -- possibly these are just cut & paste artefacts?
This thrown-together version works for me, though you may need to tweak it for your purposes:
\documentclass[11pt]{article}
\begin{document}
\begin{table}[!tbp]
\caption{Descriptive Statistics by treatment\label{f}}
\begin{center}
\begin{tabular}{lccc}
\hline
\hline
\multicolumn{1}{l}{}&\multicolumn{1}{c}{Drug}&\multicolumn{1}{c}{Placebo}&\multicolumn{1}{c}{Test Statistic}
\tabularnewline
&\multicolumn{1}{c}{{\scriptsize $N=263$}}&\multicolumn{1}{c}{{\scriptsize $N=237$}}&
\tabularnewline
\hline
age&{\scriptsize 46.5~}{49.9 }{\scriptsize 53.2} &{\scriptsize 46.7~}{50.0 }{\scriptsize 53.4} &$ F_{1,498}=0.1 ,~ P=0.754 ^{1}$
\tabularnewline
sex~:~m&47\%~{\scriptsize~(123)}&44\%~{\scriptsize~(104)}&$ \chi^{2}_{1}=0.42 ,~ P=0.517 ^{2} $
\tabularnewline
Primary~Symptoms~:~Depressed&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Headache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Hangnail&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Muscle~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
~~~~Stomach~Ache&0\%~{\scriptsize~(0)}&0\%~{\scriptsize~(0)}&$^{2}$
\tabularnewline
\hline
\end{tabular}
\end{center}
\noindent {\scriptsize $a$\ }{$b$\ }{\scriptsize $c$\ } represent the lower quartile $a$, the median $b$, and the upper quartile $c$ for continuous variables.\\
Numbers after percents are frequencies.\\
\indent Tests used:\\
\textsuperscript{\normalfont 1}Wilcoxon test;
\textsuperscript{\normalfont 2}Pearson test
\end{table}
\end{document}

If you use the package stargazer (available on CRAN), you can use the argument out="filename.tex" to output the LaTeX code directly into a Tex document. That document should then be easy to compile.

It sounds like you may not have a document class defined, or you are not using a document class that defines the table environment.

Related

In latex how to escape "{" in \verb in tabularx environmnet?

I tried \verb|\{|, and it will print \{. If using \verb|{| without the backslash, an error would occur that says ! File ended while scanning \TX#get#body
Use the following to replicate this error on Overleaf or WinEdt:
\documentclass{article}
\usepackage{tabularx}
\begin{document}
\begin{table}
\begin{tabularx}{\textwidth}{ll}
\hline
\verb|{| & Error. \\ % The use of \verb|{| here generates the error!
\hline
\end{tabularx}
\end{table}
\end{document}
I the above code, "\verb|{|" will generate the error.
With the kind help from samcarter_is_at_topanswers.xyz, I understand now that "{" can be displayed in tabularx using \listinline{{}. But this gives a plain-text style "{". Is there a way to make the "{" more code style? See the below picture for comparison.
You can use the listings package:
\documentclass{article}
\usepackage{tabularx}
\usepackage{listings}
\begin{document}
\begin{table}
\begin{tabularx}{\textwidth}{lX}
\hline
\lstinline{\}} & Error. \\
\hline
\end{tabularx}
\end{table}
\end{document}

knitr file ended while scanning use of \#xverbatim

I have the following .Rnw file:
\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{multicol}
\begin{document}
\begin{multicols}{2}
\hskip-3.5cm\begin{tabular}{|l|}
\hline
\cellcolor[RGB]{0,0,140}{\large\textbf{\textcolor{white}{Bill To: }}}\\
\hline
\textbf{
"asdf"
}\\
\\[-1em]
\textbf{asdf#asdf.com} \\
\hline
\end{tabular}
\hskip6cm\begin{tabular}{|l|l|}
\hline
Date: & 05/31/2018 \\
\hline
Invoice \#: & 1234asdf \\
\hline
\end{tabular}
\end{multicols}
\end{document}
which gives me the expected pdf:
However, when I replace the "asdf" with R code:
\documentclass{article}
\usepackage[table]{xcolor}
\usepackage{multicol}
\begin{document}
\begin{multicols}{2}
\hskip-3.5cm\begin{tabular}{|l|}
\hline
\cellcolor[RGB]{0,0,140}{\large\textbf{\textcolor{white}{Bill To: }}}\\
\hline
\textbf{
<<asdf>>=
cat("asdf")
#
}\\
\\[-1em]
\textbf{asdf#asdf.com} \\
\hline
\end{tabular}
\hskip6cm\begin{tabular}{|l|l|}
\hline
Date: & 05/31/2018 \\
\hline
Invoice \#: & 1234asdf \\
\hline
\end{tabular}
\end{multicols}
\end{document}
I get the following error:
File ended while scanning use of \#xverbatim
Looking at the generated .tex file, this is the relevant part:
\textbf{
\begin{knitrout}
\definecolor{shadecolor}{rgb}{0.969, 0.969, 0.969}\color{fgcolor}\begin{kframe}
\begin{alltt}
\hlkwd{cat}\hlstd{(}\hlstr{"asdf"}\hlstd{)}
\end{alltt}
\begin{verbatim}
## asdf
\end{verbatim}
\end{kframe}
\end{knitrout}
}\\
and this is what the .log file says:
Runaway argument?
#### asdf \end {verbatim} \end {kframe} \end {knitrout} \check#icr \expandafte
r \ETC.
! File ended while scanning use of \#xverbatim.
<inserted text>
\par
<*> test2.tex
I suspect you have forgotten a `}', causing me
to read past where you wanted me to stop.
I'll try to recover; but if the error is serious,
you'd better type `E' or `X' now and fix your file.
! Emergency stop.
<*> test2.tex
What am I doing wrong?
By default, R output is wrapped in a LaTeX verbatim environment, and you can't put one of those inside \textbf. There are a couple of different approaches to fix this.
The simplest is just to use the chunk option results='asis', i.e.
\textbf{
<<asdf,results='asis',echo=FALSE>>=
cat("asdf")
#
}
This will prevent knitr from adding the environment around the output; the LaTeX code will just be
\textbf{
asdf
}
which should be fine.
If you want the default formatting but just want to change the font or style of text, things are harder. You need to tell knitr to use a different environment instead of verbatim, e.g. the Verbatim environment provided by the fancyvrb package. You can do this by changing the output hook. For example, this should work
% in the preamble:
\usepackage{fancyvrb}
<<include=FALSE>>=
oldhook <- knitr::knit_hooks$get("output")
bold <- function(x, options)
paste0("\\begin{Verbatim}[fontseries=b]\n", x, "\\end{Verbatim}")
#
% in the body:
<<asdf,echo=FALSE>>=
knitr::knit_hooks$set(output = bold)
cat("asdf")
#
% Optionally restore the old hook...
<<include=FALSE>>=
knitr::knit_hooks$set(output = oldhook)
#
However, it doesn't always work, because some options (like fontseries=b) conflict with settings that knitr makes. You can change to italic (using fontshape=it), but not to bold. So stick with the first suggestion.

LaTeX align environment missing $ inserted

I'm using an Align environment inside of a proof, and I'm getting the error "Missing $ inserted." I've commenting out all but the first line of the align makes the error go away, but I still can't figure out what the problem is. No solution I could find works. Am I missing something?
\documentclass[12pt,letterpaper]{article}
\usepackage{ifpdf, enumerate}
\usepackage{mla}
\usepackage{gb4e}
\usepackage{amsfonts}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{stmaryrd}
\newcommand{\tuple}[1]{\ensuremath{\left \langle #1 \right \rangle }}
\newcommand{\evaluation}[2][]{\ensuremath{\llbracket #2\rrbracket^{#1}}}
\begin{document}
\begin{proof}
\begin{align*}
\evaluation[\mathbb{M}]{(Mx)(D (x) \& V (x))} = 1 \iff \\
\evaluation[\mathbb{M}]{\lbrack \alpha / x \rbrack (D (x) \& V (x))} = 1 \text{for most constants \alpha} \\
\evaluation[\mathbb{M}]{(D (\alpha) \& V (\alpha))} = 1 \text{for most constants \alpha } \\
\evaluation[\mathbb{M}]{D (\alpha)} = 1 \text{and} \evaluation[\mathbb{M}]{V (\alpha)} = 1 \text{for most constants \alpha } \\
F(\alpha) \in F(D) \text{and} F(\alpha) \in F(V) \text{for most constants \alpha } \\
\intertext{Examining the definitions of the model, we see that there are only four entities that are both in $F(D)$ and $F(V)$: Alice, Bob, Colin, and David. Because this is not more than half of the total twelve entities in the universe, our naive definition of ``most'' is not satisfied. Therefore the statement is false, which implies that the truth value of the origenal proposition is not 1.}
\end{align*}
\end{proof}
\end{document}
Here is what the error message looks like.
./test.tex:24: Missing $ inserted.
<inserted text>
$
l.24 \end{align*}
?
You've missed only one tricky fact: \alpha only works in math mode, so if you replace all occurrences of
\text{for most constants \alpha} \\
(lines 18, 19, 20, 21) with
\text{for most constants }\alpha \\
then your tex will compile sweetly. Also:
\text{for most constants}\ \alpha \\
or:
\text{for most constants $\alpha$} \\
as you already did in line 22 of your code (...$F(D)$ and $F(V)$...).
This answer is not applicable to this exact case, but the given error can also pop up if the "amsmath" package is not being used. It becomes tricky because the whole code looks alright except I had forgotten to add the \usepackage{amsmath} line in the beginning of the document.

Using the booktabs \midrule and with brackets

I am having trouble using \midrule in a latex longtable along with brackets. For example, here is my latex document (test.tex):
\documentclass[a4paper]{article}\usepackage[]{graphicx}\usepackage[]{color}
\usepackage{longtable}
\usepackage{booktabs}
\begin{document}
\begin{longtable}{|l|l|}
\caption{} \\
\toprule
test & estimate\\
\midrule
(Intercept) & 10.000 \\
test & 20.000 \\
\bottomrule
\end{longtable}
\end{document}
When running pdflatex on this file:
pdflatex test.tex
I run into these errors:
! Undefined control sequence.
<argument> ...al \expandafter \let \cmrsideswitch
\#tempa \fi \fi
l.12 (Intercept)
& 10.000 \\
Removing the brackets fixes the issue. And interestingly switching the order of the 2 rows works too [i.e. the (Intercept) row as the second row). I can't figure out what is wrong. Has anyone encountered this?
OK, so I had the same problem with code generated from Pandoc (with bracket after \toprule), I fixed it by using \toprule{} instead, it seems that toprule eats the bracket otherwise. Maybe this will help you.
Another possibilty is to put empty \hbox{} before the opening bracket, which I used, since I could not modify tex produced by pandoc (but pandoc is capable of parsing latex snippets in markdown).

How to create a \newenvironment in latex for a scaled table

I try to define a table as a new environment.
\newenvironment{scaledtable}[1]{%
\begin{table}[h]
\caption{xxx}
\label{tab:xxx}
\begin{center}
\begin{tabular}{rcrrrrrrrrrrrrcc}
}{
\hline
\end{tabular}
\end{center}
\end{table}}
The problem I have is that I can't use scalebox{}. If I put the closing bracket into the end definition of the environment, latex can't assign the brackets anymore. I also can not use PStricks because of pdflatex.
Use \lrbox to temporarily store the table, then scale it
\newsavebox{\scaledtablebox}
\newcommand*{\scaledtablefactor}{1}
\newenvironment{scaledtable}[1]{%
\renewcommand*{\scaledtablefactor}{#1}%
\begin{table}[h]%
\caption{xxx}%
\label{tab:xxx}%
%
\begin{lrbox}{\scaledtablebox}%
\begin{tabular}{ll}%
}{%
\hline%
\end{tabular}%
\end{lrbox}%
%
\begin{center}%
\scalebox{\scaledtablefactor}{\usebox{\scaledtablebox}}%
\end{center}%
\end{table}%
}
Works like this (0.5 is the scale factor):
\begin{scaledtable}{0.5}
Hello & World! \\
\end{scaledtable}

Resources