How to align xtable output columns?

49 Views Asked by At

I'm looking for something that should be quite simple, but I cannot find a way to do this. Very frustrating that there is no easy-to-follow documentation on xtable.

I have a dataframe:

> df <- structure(list(Coefficient = c("-0.148", "", "", ""), SE = c(" 0.148", 
"388", "13,451", "13,254.94"), p = c(" 0.316", "", "", "")), class = "data.frame", row.names = c("Male", 
"Individuals", "Intervals", "Years"

> df

              Coefficient        SE      p
Male               -0.148     0.148  0.316
Individuals                     388       
Intervals                    13,451       
Years                     13,254.94       

I want to convert it to latex, like so:

> print(xtable(df))

\begin{table}[ht]
\centering
\begin{tabular}{rlll}
  \hline
 & Coefficient & SE & p \\ 
  \hline
Male & -0.148 &  0.148 &  0.316 \\ 
  Individuals &  & 388 &  \\ 
  Intervals &  & 13,451 &  \\ 
  Years &  & 13,254.94 &  \\ 
   \hline
\end{tabular}
\end{table}

Notice \begin{tabular}{rlll} in the latex table which defines column alignment. How do I change this? I want \begin{tabular}{lccc}.

This question is obviously suited for this community because I am asking how to format the latex table using an R, and not a duplicate because I am not asking for individual cell alignment.

Any help is appreciated.

1

There are 1 best solutions below

0
Grzegorz Sapijaszko On

Use align option of xtable(), like:

df <- structure(list(Coefficient = c("-0.148", "", "", ""), SE = c(
  " 0.148",
  "388", "13,451", "13,254.94"
), p = c(" 0.316", "", "", "")), class = "data.frame", row.names = c(
  "Male",
  "Individuals", "Intervals", "Years"
))
df
#>             Coefficient        SE      p
#> Male             -0.148     0.148  0.316
#> Individuals                   388       
#> Intervals                  13,451       
#> Years                   13,254.94

 print(xtable::xtable(df,
                      align=c("l","c","c","c")))
#> % latex table generated in R 4.2.1 by xtable 1.8-4 package
#> % Thu Jul  6 16:49:38 2023
#> \begin{table}[ht]
#> \centering
#> \begin{tabular}{lccc}
#>   \hline
#>  & Coefficient & SE & p \\ 
#>   \hline
#> Male & -0.148 &  0.148 &  0.316 \\ 
#>   Individuals &  & 388 &  \\ 
#>   Intervals &  & 13,451 &  \\ 
#>   Years &  & 13,254.94 &  \\ 
#>    \hline
#> \end{tabular}
#> \end{table}

Created on 2023-07-06 with reprex v2.0.2