Using Xtable with R and Latex, Math Mode in Column Names

Using xtable with R and Latex, math mode in column names?

as suggested in the xtable gallery vignette you should use a sanitization function (as unikum also suggested).
Just some dummy code how I got it working with your example:

library(xtable)
adf.results<-matrix(0,ncol=6,nrow=4)
colnames(adf.results) <- c(" ", "$m^r_t$", "$\\delta p_t$","$R^r_t$", "$R^b_t$", "$y^r_t$")
print(xtable(adf.results),sanitize.text.function=function(x){x})

Good luck with it.

Kind regards,

FM

Problems forming a LaTeX table using xtable-package in R

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}

Sample Image

xtable rownames using R

Try running just the R code, and you'll get a warning that tells you why the row names aren't showing up:

library(xtable)
table.matrix <- matrix(numeric(0), ncol = 5, nrow = 12)
colnames(table.matrix) <- c("$m_t$", "$p_t$", "$R^b_t$", "$R^m_t$", "$y^r_t$")
rownames(table.matrix) <- c("$m_{t-1}$", " ", "$p_{t-1}$", " ", "$R^b_{t-1}$", " ", "$R^m_{t-1}$", " ", "$y^r_t$", " ", "$c$", " ")

xtable(table.matrix)
# Warning message:
# In data.row.names(row.names, rowsi, i) :
# some row.names duplicated: 4,6,8,10,12 --> row.names NOT used

So you can't have duplicated rownames in R. You could solve this by making a name "column" instead of using rownames.

How to put a newline into a column header in an xtable in R

The best way I have found to do this is to indicate the table column as a "fixed width" column so that the text inside it wraps. With the xtable package, this can be done with:

align( calqc_xtable ) <- c( 'l', 'p{1.5in}', rep('c',5) )

xtable demands that you provide an alignment for the option "rownames" column- this is the initial l specification. The section specification, p{1.5in}, is used for your first column header, which is quite long. This limits it to a box 1.5 inches in width and the header will wrap onto multiple lines if necessary. The remaining five columns are set centered using the c specifier.

One major problem with fixed width columns like p{1.5in} is that they set the text using a justified alignment. This causes the inter-word spacing in each line to be expanded such that the line will fill up the entire 1.5 inches allotted.

Frankly, in most cases this produces results which I cannot describe using polite language (I'm an amateur typography nut and this sort of behavior causes facial ticks).

The fix is to provide a latex alignment command by prepending a >{} field to the column specification:

align( calqc_xtable ) <- c( 'l', '>{\\centering}p{1.5in}', rep('c',4) )

Other useful alignment commands are:

  • \raggedright -> causes text to be left aligned
  • \raggedleft -> causes text to be right aligned

Remember to double backslashes to escape them in R strings. You may also need to disable the string sanitation function that xtable uses by default.

Note

This alignment technique will fail if used on the last column of a table unless table rows are ended with \tabularnewline instead of \\, which I think is not the case with xtable and is not easily customizable through any user-settable option.

The other thing to consider is that you may not want the entire column line-wrapped to 1.5 inches and centered- just the header. In that case, disable xtable string sanitization and set your header using a \multicolumn cell of width 1:

names(calqc_table)[1]<-"\\multicolumn{1}{>{\\centering}p{1.5in}}{Identifier of the Run within the Study}"

How to set spaces in the column names of a table or data frame using xtable

Your best bet is probably to use the sanitize.* options, e.g.:

> print.xtable(xtable(dat),include.rownames=F,
sanitize.colnames.function=function(x)gsub("\\."," ",x))

% latex table generated in R 3.2.1 by xtable 1.7-4 package
% Thu Aug 20 10:47:54 2015
\begin{table}[ht]
\centering
\begin{tabular}{llll}
\hline
Variable & Categoría de Referencia & Categoría Considerada & Variación \\
\hline
Uso & No Acaba Unidad & Acaba la Unidad & 2.08\% \\
País & Brasil & España & 0.31\% \\
País & Brasil & Francia & 0.46\% \\
País & Brasil & ITalia & 0.7\% \\
País & Brasil & Méjico & -0.19\% \\
País & Brasil & Otros Países & -0.46\% \\
Clicker & Clicker & No Cliker & -2.32\% \\
App & No Usa App & Usa App & 1.15\% \\
\hline
\end{tabular}
\end{table}

From ?print.xtable:

sanitize.text.function
All non-numeric enteries (except row and column names) are sanitised in an attempt to remove characters which have special meaning for the output format. If sanitize.text.function is not NULL (the default), it should be a function taking a character vector and returning one, and will be used for the sanitization instead of the default internal function

This is the same for sanitize.colnames.function.

Another option in case you'd like a total overhaul of the names (so that you can't regex your way to freedom as above) is to convert dat to a matrix and set the colnames:

datmat<-as.matrix(dat)
colnames(datmat)<-c("Variable","Categoría de Referencia",
"Categoría Considerada", "Variación")
print.xtable(xtable(datmat),include.rownames=F)

xtable and header alignment

To do that in LaTeX you stick your headers into a \multicolumn thing to specify the alignment you want:

\begin{tabular}{rrr}
\hline
& \multicolumn{1}{c}{x} &\multicolumn{1}{c}{y} \\
\hline
1 & 1 & 0.17 \\
2 & 2 & 0.63 \\
3 & 3 & 0.95 \\
4 & 4 & 0.57 \\
5 & 5 & 0.65 \\
\hline
\end{tabular}

The print.xtable function uses the names of the xtable object as the headers. So if you rename your xtable object:

> d=data.frame(x=1:5,y=runif(5))  # sample data frame
> dx=xtable(d) # make an xtable
> names(dx)=c("\\multicolumn{1}{c}{x}","\\multicolumn{1}{c}{y}")

then that's most of the work done, you just have to print it overriding the sanitization function of print.xtable:

> print.xtable(dx,sanitize.colnames.function=function(x){x})
% latex table generated in R 2.15.1 by xtable 1.7-0 package
% Thu Feb 21 15:28:11 2013
\begin{table}[ht]
\begin{center}
\begin{tabular}{rrr}
\hline
& \multicolumn{1}{c}{x} & \multicolumn{1}{c}{y} \\
\hline
1 & 1 & 0.78 \\
2 & 2 & 0.34 \\
3 & 3 & 0.88 \\
4 & 4 & 0.45 \\
5 & 5 & 0.54 \\
\hline
\end{tabular}
\end{center}
\end{table}

otherwise it does

& $\backslash$multicolumn\{1\}\{c\}\{x\} & $\backslash$multicolumn\{1\}\{c\}\{y\} \\ 

How's that?



Related Topics



Leave a reply



Submit