Mayou
Mayou

Reputation: 8828

Print matrix to pdf in R

I would like to know if there is any R package that allows for "pretty" printing of matrices/dataframes to pdf: by "pretty", I mean being able to print a matrix with brackets to a pdf:

enter image description here

Upvotes: 0

Views: 2220

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226427

This is a hand-rolled solution that outputs a matrix to an array environment in a standalone LaTeX file; you may be able to customize Hmisc::latex for better results.

m <- matrix(c(23,5,2,34,4,4,3,4,26),
             byrow=TRUE,ncol=3)
unlink("outfile.tex")  ## danger
ff <- file("outfile.tex",open="a")
writeLines(c("\\documentclass{article}",
             "\\begin{document}",
             "$$",
             "\\left(",
             "\\begin{array}{ccc}"),
             con=ff)
write.table(m,sep=" & ", eol="\\\\", row.names=FALSE,
            col.names=FALSE,append=TRUE,
            file=ff)
writeLines(c("\\end{array}",
             "\\right)",
             "$$",
             "\\end{document}"),
           con=ff)
close(ff)               

With a little bit of extra work this could be generalized to a function that recognized the number of columns in the matrix, took an output file name as an argument, etc. -- but it might be reinventing part of Hmisc::latex().

Upvotes: 2

Related Questions