[R] printing an arbitrary-length character vector in columns on a page of a pdf report

Berry, Charles ccberry @end|ng |rom uc@d@edu
Wed Jun 6 04:33:07 CEST 2018

> On Jun 5, 2018, at 9:45 AM, Christopher W Ryan <cryan using binghamton.edu> wrote:
> I'm writing code for a recurring report, using an R --> Sweave --> pdflatex
> workflow. It includes a character vector of short words that I would like
> to display compactly, in columns on a page, rather than one word per line,
> which would waste a lot of space. The vector of words will increase
> unpredictably over time, with future versions of the report.
> I thought I would go about it by turning the character vector into a
> matrix, as follows:
> dd <- LETTERS
> ## set number of columns. Three for now
> nc <- 3
> ## have to pad the character vector to a length that is multiple of nc
> add <- nc - (length(dd) %% nc)
> dd2 <- c(dd, rep("", add))
> ddm <- matrix(dd2, ncol = nc)
> library(Hmisc)
> latex(ddm, file = "")
> Any ideas for a more elegant way to do this?

Use a LaTeX longtable environment (and add \usepackage{longtable} to the header of your document). Put something like this in your *.Rnw file:

% longtable header goes here

cat( paste(dd, ifelse( seq(along = dd) %% 3 == 0, "\\\\\n", "&")) )

% longtable footer goes here

should do it. But if there are exactly 3*k elements, you might skip the trailing `\\'.

If you are unclear what the header/footer ought to look like try this:

HMisc::latex(ddm, file="", longtable=TRUE)

and you should figure it out.



More information about the R-help mailing list