7

Please consider the following MWE

library(xtable)
DF <- as.data.frame(UCBAdmissions)
print(xtable(DF, align="p{0.4\textwidth}|p{0.15\textwidth} p{0.15\textwidth} p{0.15\textwidth}"), sanitize.text.function = function(x){x}, 
      table.placement="!htp", include.rownames=FALSE, 
      tabular.environment='longtable',floating=FALSE)

I want to set the alignment of my longtable like

\begin{longtable}{p{0.4\textwidth}|p{0.15\textwidth} p{0.15\textwidth} p{0.15\textwidth}}

Still when I try to pass the argument to a xtable object I get

Warning message:
In .alignStringToVector(value) : Nonstandard alignments in align string
Error in print(xtable(DF, align = "p{0.4\textwidth}|p{0.15\textwidth} p{0.15\textwidth} p{0.15\textwidth}"),  : 
  error in evaluating the argument 'x' in selecting a method for function 'print': Error in `align<-.xtable`(`*tmp*`, value = "p{0.4\textwidth}|p{0.15\textwidth} p{0.15\textwidth} p{0.15\textwidth}") : 
  "align" must have length equal to 5 ( ncol(x) + 1 )

I understand I should add the alignment for a 5th column (how?) but also I don't understand the error message. Should I sanitize the string?

CptNemo
  • 6,455
  • 16
  • 58
  • 107

1 Answers1

12

I am unable to test this but I think you need to apply standard R escaping to backslashes in a string , remove the extraneous "\" and add the missing "pipe bars" (|). Then the align<- succeeds with only a warning:

xtb <- xtable(DF, 
       table.placement="!htp", include.rownames=FALSE, 
       tabular.environment='longtable',floating=FALSE)
align(xtb) <- "p{0.4\\textwidth}|p{0.15\\textwidth}|p{0.15\\textwidth}| p{0.15\\textwidth}"
#Warning message:
#In .alignStringToVector(value) : Nonstandard alignments in align string
 print(xtb)

Or:

xtb <- xtable(DF, type="latex",
      table.placement="!htp", include.rownames=FALSE, 
      tabular.environment='longtable',floating=FALSE, align= c("p{0.15\\textwidth}", 
"p{0.4\\textwidth}", "p{0.15\\textwidth}|", "p{0.15\\textwidth}", "p{0.15\\textwidth}"
))
IRTFM
  • 258,963
  • 21
  • 364
  • 487
  • 1
    How to escape? This doens't work `align="p\\{0.4\\textwidth\\}p\\{0.15\\textwidth\\} p\\{0.15\\textwidth\\}")` – CptNemo Jan 01 '14 at 07:46
  • 1
    Separating the formats into separate character elements seemed to succeed: – IRTFM Jan 01 '14 at 08:25
  • 2
    Note: I tried escaping the curley braces as described in the help page but got errors. – IRTFM Jan 01 '14 at 17:08
  • The second method of @IShouldBuyABoat works for the curly braces without any need to escape them. – imriss Mar 20 '14 at 18:03