Skip to content

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

5 messages · Christopher W. Ryan, Charles C. Berry, Richard M. Heiberger

#
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?

Thanks.

--Chris Ryan
Binghamton University
and
Broome County Health Department
Binghamton, NY, US
#
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

<<results=tex>>=
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.

HTH,

Chuck
#
I think this is cuter, and it is a hair faster.

n <- length(dd)
ddm <- matrix("", (n+2) %/% nc, nc)
ddm[1:n] <- dd

Rich
+ add <- nc - (length(dd) %% nc)
+ dd2 <- c(dd, rep("", add))
+ ddm <- matrix(dd2, ncol = nc)
+ })
   user  system elapsed
  0.064   0.100   0.483
+ n <- length(dd)
+ ddm <- matrix("", (n+2) %/% nc, nc)
+ ddm[1:n] <- dd
+ })
   user  system elapsed
  0.045   0.000   0.045

On Tue, Jun 5, 2018 at 12:45 PM, Christopher W Ryan
<cryan at binghamton.edu> wrote:
#
Richard--

Nice. If I understand your code correctly, in the line

ddm <- matrix("", (n+2) %/% nc, nc)

I could instead use

ddm <- matrix("", (n + nc - 1) %/% nc, nc)

for generalizability, as I may have to increase nc as the list of words
grows ever longer.

Thanks everyone. Several good suggestions.

--Chris Ryan
Richard M. Heiberger wrote:
#
yes, thank you for catching that slip.

On Tue, Jun 5, 2018 at 11:29 PM, Christopher W. Ryan
<cryan at binghamton.edu> wrote: