Question

I have this data.frame which I'm trying to convert to latex code using stargazer:

habitats_df <- data.frame(habitat = c("beach", "grassland", "freshwater"), v1 = c(0.000, 0.670, 0.032), v2 = c(0.005, 0.824, 0.012))


 library(stargazer)
stargazer(habitats_df, summary = F)

 % Table created by stargazer v.4.5.3 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu
    % Date and time: Wed, Jan 22, 2014 - 11:11:44
    \begin{table}[!htbp] \centering 
      \caption{} 
      \label{} 
    \begin{tabular}{@{\extracolsep{5pt}} ccc} 
    \\[-1.8ex]\hline 
    \hline \\[-1.8ex] 
    habitat & v1 & v2 \\ 
    \hline \\[-1.8ex] 
    beach & $0$ & $0.005$ \\ 
    grassland & $0.670$ & $0.824$ \\ 
    freshwater & $0.032$ & $0.012$ \\ 
    \hline \\[-1.8ex] 
    \normalsize 
    \end{tabular} 
    \end{table} 

Note stargazer is printing table in maths mode, therefore it enclosing numbers with $. How can I stop stargazer from printing table in latex maths mode?

Was it helpful?

Solution

Convert any numeric columns that you don't want as numeric to character:

habitats_df$v1 <- as.character(habitats_df$v1)
> stargazer(habitats_df, summary = F)

% Table created by stargazer v.4.5.3 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu
% Date and time: Wed, Jan 22, 2014 - 11:23:59
\begin{table}[!htbp] \centering 
  \caption{} 
  \label{} 
\begin{tabular}{@{\extracolsep{5pt}} ccc} 
\\[-1.8ex]\hline 
\hline \\[-1.8ex] 
habitat & v1 & v2 \\ 
\hline \\[-1.8ex] 
beach & 0 & $0.005$ \\ 
grassland & 0.67 & $0.824$ \\ 
freshwater & 0.032 & $0.012$ \\ 
\hline \\[-1.8ex] 
\normalsize 
\end{tabular} 
\end{table} 

As for the "why", it's because otherwise numbers aren't typeset correctly. If you have negative values, math mode will use a longer dash, and it will allow LaTeX to control the number of digits printed. Otherwise, as you can see above, if you want to exert control over the number of digits, you'll have to do that using sprintf in R.

OTHER TIPS

Hmisc:: latexSN does the job nicely.

habitats_df$v1 <- latexSN(habitats_df$v1)
habitats_df$v2 <- latexSN(habitats_df$v2)

library(stargazer)
stargazer(habitats_df, summary = F)

% Table created by stargazer v.4.5.3 by Marek Hlavac, Harvard University. E-mail: hlavac at fas.harvard.edu
% Date and time: Fri, Jan 24, 2014 - 08:32:39
\begin{table}[!htbp] \centering 
  \caption{} 
  \label{} 
\begin{tabular}{@{\extracolsep{5pt}} ccc} 
\\[-1.8ex]\hline 
\hline \\[-1.8ex] 
habitat & v1 & v2 \\ 
\hline \\[-1.8ex] 
beach & 0.000 & 0.005 \\ 
grassland & 0.670 & 0.824 \\ 
freshwater & 0.032 & 0.012 \\ 
\hline \\[-1.8ex] 
\normalsize 
\end{tabular} 
\end{table}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top