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

后端 未结 2 921
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 10:34

I have a dataframe that I am putting into a sweave document using xtable, however one of my column names is quite long, and I would like to break it over two lines to save space

2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-31 11:38

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

提交回复
热议问题