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

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}"


@Sharpie 's technique did not work for me, as pandoc failed with error 43 on conversion to pdf. Therefore, here is what I did:

moved the \\centering marker:

names(calqc_table)=c(rep("\\multicolumn{1}{p{0.75in}}{\\centering Identifier of the Run within the Study}", 6))

(here applied to all 6 columns of the table)

and disabled sanitization in xtable printing:

print(calqc_table, sanitize.colnames.function=function(x){x})