Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting R matrix into LaTeX matrix in the math or equation environment

Tags:

r

latex

knitr

Let's say there is an R matrix x:

x <- structure(c(2, 3, 5, 7, 9, 12, 17, 10, 18, 13), .Dim = c(5L,2L), .Dimnames = list(NULL, c("X1", "X2")))

I am writing a report featuring LaTeX equations, using the Markdown-pandoc-LaTeX workflow. x is one of the matrices that need to appear in these equations. Is it possible to programmatically render the LaTeX respresentation of the matrix as follows?:

\begin{bmatrix}
2 & 12\\ 
3 & 17\\ 
5 & 10\\ 
7 & 18\\ 
9 & 13
\end{bmatrix}

Ideally the report code would be something in the lines of:

\begin{displaymath}
\mathbf{X} = `r whatever-R-code-to-render-X`
\end{displaymath}

but this is probably cumbersome, so I will surely settle for the simple transformation.

like image 909
Maxim.K Avatar asked Dec 23 '13 18:12

Maxim.K


1 Answers

You can use the xtable packages print.xtable method with a simple wrapper script to set some default args.

bmatrix = function(x, digits=NULL, ...) {
  library(xtable)
  default_args = list(include.colnames=FALSE, only.contents=TRUE,
                      include.rownames=FALSE, hline.after=NULL, comment=FALSE,
                      print.results=FALSE)
  passed_args = list(...)
  calling_args = c(list(x=xtable(x, digits=digits)),
                   c(passed_args,
                     default_args[setdiff(names(default_args), names(passed_args))]))
  cat("\\begin{bmatrix}\n",
      do.call(print.xtable, calling_args),
      "\\end{bmatrix}\n")
}

Seems to do what you are looking for

x <- structure(c(2, 3, 5, 7, 9, 12, 17, 10, 18, 13), .Dim = c(5L,2L), .Dimnames = list(NULL, c("X1", "X2")))

bmatrix(x)
## \begin{bmatrix}
##   2.00 & 12.00 \\ 
##   3.00 & 17.00 \\ 
##   5.00 & 10.00 \\ 
##   7.00 & 18.00 \\ 
##   9.00 & 13.00 \\ 
##    \end{bmatrix}

And to use no decimal places like your example.

bmatrix(x, digits=0)
## \begin{bmatrix}
##   2 & 12 \\ 
##   3 & 17 \\ 
##   5 & 10 \\ 
##   7 & 18 \\ 
##   9 & 13 \\ 
##    \end{bmatrix}
like image 199
Jim Avatar answered Oct 16 '22 19:10

Jim