Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get LaTeX table from latex() in Hmisc to align columns

Tags:

r

latex

I have some problems getting the align to work in my latex table, here's an example:

library(Hmisc)
set.seed(1)
x <- matrix(round(runif(6*3)*10, 2), ncol=6)
x[1, 2] <- -round(x[1, 2], 0)
x[3, 3] <- -round(x[1, 2], 1)
x[3, 5] <- round(x[1, 2], 1)

ci1 <- apply(x[,2:3], 1, FUN=function(x){
        ret <- paste(min(x), "-", max(x))
        return(ret)
})
ci2 <- apply(x[,5:6], 1, FUN=function(x){
        ret <- paste(min(x), "-", max(x))
        return(ret)
})

x <- cbind(x[,1], ci1, x[,4], ci2)
colnames(x) <- c("A", "interval", "B", "interval")
rownames(x) <- sapply(letters[1:3], FUN=function(x){ return(paste("Var_", x, sep=""))})

latex(x, file="", align="rcrc", rowlabel.just="r", 
      cgroup = c("First", "Second"), 
      n.cgroup = c(2, 2),
      rgroup=c("Grup A and B", "Group C"), 
      n.rgroup=c(2, NROW(x) - 2), 
      ctable=T)

This produces:

% latex.default(x, file = "", align = "rcrc", rowlabel.just = "r",      cgroup = c("First", "Second"), n.cgroup = c(2, 2), rgroup = c("Grup A and B",          "Group C"), n.rgroup = c(2, NROW(x) - 2), ctable = T) 
%
\ctable[ label=x, pos=!tbp, ]{rllcll} {} {\FL\multicolumn{1}{c}{\bfseries x}&
\multicolumn{2}{c}{\bfseries First}&
\multicolumn{1}{c}{\bfseries }&
\multicolumn{2}{c}{\bfseries Second}
\NN \cline{2-3} \cline{5-6}
\multicolumn{1}{r}{}&\multicolumn{1}{c}{A}&\multicolumn{1}{c}{interval}&\multicolumn{1}{c}{}&\multicolumn{1}{c}{B}&\multicolumn{1}{c}{interval}\NN
\ML
{\bfseries Grup A and B}&&&&&\NN
Var_a&2.66&-9 - 9.45&&0.62&4.98 - 6.87\NN
Var_b&3.72&2.02 - 6.61&&2.06&3.84 - 7.18\NN
\ML
{\bfseries Group C}&&&&&\NN
Var_c&5.73&8.98 - 9&&1.77&-9 - 9.92\NN
\LL
}

The error is here:

\ctable[ label=x, pos=!tbp, ]{rllcll}

I want rllcll to be rrccrc but it doesn't do that. I have tried all possible alternatives for the aling and halign parameter. It's a little annoying to be doing this by hand...

like image 239
Max Gordon Avatar asked Nov 26 '11 17:11

Max Gordon


1 Answers

Here is the way to do it. The main changes to the code is to use col.just = c('r', 'c', 'r', 'c') instead of align. Moreover, your row names have underscores, which will cause latex to throw an error. So use latexTranslate to escape your underscores and prevent error

latex(x, file="", col.just = strsplit("rcrc", "")[[1]], rowlabel.just="r", 
  cgroup = c("First", "Second"), n.cgroup = c(2, 2),
  rgroup = c("Grup A and B", "Group C"), n.rgroup=c(2, NROW(x) - 2), 
  booktabs = T, rowname = latexTranslate(rownames(x)))

enter image description here

like image 108
Ramnath Avatar answered Sep 22 '22 15:09

Ramnath