Jh00ni
Jh00ni

Reputation: 67

Problems forming a LaTeX table using xtable-package in R

I would like to form the following LaTeX-table with xtable-package in R.

enter image description here

Table 1: Wanted LaTeX table

However, I do not understand how to add multiple extra rows to xtable-function to get above table.

For example using simple code like this

financial <- c(1.23, 1.19)
  macro <- c(1.50, 1.40)
  X <- rbind(financial, macro)
  colnames(X) <- c("A","B")
X
             A    B
financial 1.23 1.19
macro     1.50 1.40

print(xtable(X), type="latex")

Now, how do you add the the extra rows, alignments, hlines(e.g., Country, United States, Method etc.) to xtable-function to the achieve above table?

I already looked at https://cran.r-project.org/web/packages/xtable/vignettes/xtableGallery.pdf but I did not find any clear anwer to my question.

Any help would be appreciated!

Upvotes: 0

Views: 613

Answers (1)

Otto K&#228;ssi
Otto K&#228;ssi

Reputation: 3083

Here's my approach (with inspiration from)

library(xtable)
financial <- c(1.23, 1.19)
  macro <- c(1.50, 1.40)
  X <- rbind(financial, macro)
  colnames(X) <- c("A","B")

addtorow <- list()
addtorow$pos <- list()
addtorow$pos[[1]] <- 0
addtorow$pos[[2]] <- 0
addtorow$pos[[3]] <- 0
addtorow$pos[[4]] <- 0
addtorow$pos[[5]] <- 0
addtorow$pos[[6]] <- 0
addtorow$pos[[7]] <- 0
addtorow$command <- c('Country: & United States & \\\\\n', 
                      '\\hline',
                      'Method: & Regression &  \\\\\n',
                      '\\hline',                      
                      'Models: & RMSE Result &  \\\\\n',
                      '\\hline',
                      '& A & B \\\\\n')

print(xtable(X), add.to.row = addtorow,  include.colnames = FALSE )

add.to.row can be used to include custom latex code into xtable.

I did could not figure out how to place your column names & A & B after the custom header. My solution for this was to use include.colnames = FALSE and manually inserted column headers in add.to.row. (perhaps someone else has a more elegant solution?)

Result:

% latex table generated in R 4.0.5 by xtable 1.8-4 package
% Mon Jan 17 14:16:51 2022
\begin{table}[ht]
\centering
\begin{tabular}{rrr}
  \hline
  Country: & United States & \\
 \hline Method: & Regression &  \\
 \hline Models: & RMSE Result &  \\
 \hline & A & B \\
 \hline
financial & 1.23 & 1.19 \\
  macro & 1.50 & 1.40 \\
   \hline
\end{tabular}
\end{table}

enter image description here

Upvotes: 2

Related Questions