Converting R matrix into LaTeX matrix in the math or equation environment
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}
How do I get (LaTeX math) typeset matrix with borders in HTML output from *.Rmd?
knitr, the tool normally used to convert RMarkdown to HTML/PDF (from LaTeX)/DOCX, uses Pandoc. Pandoc is a nice tool to convert Markdown to HTML and LaTeX and allows you to use LaTeX math environments inside Markdown, e.g.
$a x^2 + b x + c = 0$
or
$$a x^2 + b x + c = 0$$
or
\begin{equation}
a x^2 + b x + c = 0
\end{equation}
are properly converted by Pandoc. Pandoc also supports the amsmath
, a very popular LaTeX package for math. Unfortunately, Pandoc doesn't support all (La)TeX commands/environment as you discovered.
What I always do when working with Pandoc is try to keep things simple. In the case you present, I would use normal tables instead of a matrix.
matrix by matrix in R markdown
Three minor corrections should be sufficient to make this work for both, HTML and PDF output:
- remove the backslash before the closing bracket in
\right\)
- delete the empty line in the middle
- specify the column alignment in each
array
environment, e.g., with\begin{array}{cc}
-
$$
\left(\begin{array}{cc}
0.8944272 & 0.4472136\\
-0.4472136 & -0.8944272
\end{array}\right)
\left(\begin{array}{cc}
10 & 0\\
0 & 5
\end{array}\right)
$$
How to add a matrix to a LaTeX document
For a matrix of the form:
M = x y
z w
use the LaTeX code:
$M =
\begin{array}{cc}
x & y \\
z & w \\
\end{array}$
Latex matrix not displaying right numbers
As @Peter Grill mentioned, \[
already starts math mode, so you don't need align*
. If you need square brackets as delimiters you can use \left[
and \right]
commands or predefined environment bmatrix
.
\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\begin{document}
%
% Option #1
%
\[ \left[
\begin{matrix}
1 & -9 & 3 \\
1 & 2 & -2 \\
-2 & 1 & 1
\end{matrix}
\right] \]
%
% Option #2
%
\[
\begin{bmatrix}
1 & -9 & 3 \\
1 & 2 & -2 \\
-2 & 1 & 1
\end{bmatrix}
\]
\end{document}
Both approaches give the same result:
Knitr: R code within LaTeX environment in a Markdown document
This is because your matrix2latex
function uses cat
and sends its output to the standard output stream, which isn't where knitr
is trying to put the output.
Two solutions: one is to rewrite your function to construct the output as a string using paste
and sprintf
or other string formatting functions, or as a quick hack just wrap it in capture.output
thus:
m2l = function(matr){capture.output(matrix2latex(matr))}
Then in your .Rmd
file:
\begin{displaymath}
\mathbf{X} = `r m2l(x)`
\end{displaymath}
becomes
\mathbf{X} = \begin{bmatrix} , 0.06099 & 0.768 \\ , 0.6112 & 0.004696 \\ , 0.02729 & 0.6198 \\ , 0.8498 & 0.3308 \\ , 0.6869 & 0.103 \\ , \end{bmatrix}
which although isn't quite perfect does illustrate the principle. The code inserted by the inline expression is the value of it, not what it prints or cats.
For R Markdown, How do I display a matrix from R variable
This is a perfect use case for knitr::knit_print()
.
You will find details about the knitr::knit_print()
method in its dedicated vignette:
vignette('knit_print', package = 'knitr')
The goal is to provide a knit_print
method for objects of class matrix
. As other answers suggested, it could be useful to define operators.
You will find below an Rmd
file that provides a solution to your problem. It also contains a proposal for operators.
The main feature of this answer is that you only have to write
`r A`
to output the matrix A in LaTeX inline mode (no $
to type) and write
```{r echo=FALSE}
A
```
to write in LaTeX display mode.
I also propose you to define a %times%
operator. Therefore, you only have to write:
`r A %times% B`
This answer is quite generic and you should be able to extend it to other objects.
---
title: "R Markdown: Display a Matrix for R Variable"
author: "Romain Lesur"
output:
html_document:
keep_md: true
---
```{r setup, include=FALSE}
# Define a generic method that transforms an object x in a LaTeX string
as_latex = function(x, ...) {
UseMethod('as_latex', x)
}
# Define a class latex for LaTeX expressions
as_latex.character = function(x) {
structure(
paste(x, collapse = ' '),
class = c('latex', 'character')
)
}
# A character string of class latex is rendered in display mode
# Define a knit_print() method for the latex class
knit_print.latex = function(x, ...) {
knitr::asis_output(
paste0('$$', x, '$$')
)
}
# Now, define a method as_latex for matrix
as_latex.matrix = function(x, ...) {
as_latex(c(
'\\begin{bmatrix}',
paste(
t(x),
rep(c(rep('&', nrow(x) - 1), '\\\\'), ncol(x)),
collapse = ''
),
'\\end{bmatrix}'
))
}
# Indicate to knitr that matrix are rendered as latex
knit_print.matrix = function(x, ...) {
knitr::knit_print(as_latex(x))
}
# Build a knitr inline hook to display inline latex in inline mode
default_inline_hook = knitr::knit_hooks$get('inline')
knitr::knit_hooks$set(inline = function(x) {
x = paste(gsub('\\$\\$', '$', x))
default_inline_hook(x)
})
```
```{r}
A = matrix(c(1,3,0,1),2,2)
B = matrix(c(5,3,1,4),2,2)
```
Now, matrix are rendered as LaTeX:
Matrix A in inline mode: `r A`
Matrix A in display mode:
```{r echo=FALSE}
A
```
### Operators
As other answers suggested, it could be useful to define operators.
With the previous class, it is relatively straightforward:
```{r operators, include=FALSE}
`%times%` = function(x, y) {
as_latex(sapply(list(x, '\\times', y), as_latex))
}
`%add%` = function(x, y) {
as_latex(sapply(list(x, '+', y), as_latex))
}
```
Example in inline mode: `r A %add% A %times% B`
Display mode:
```{r echo=FALSE}
A %times% B
```
Related Topics
Create All Possible Combiations of 0,1, or 2 "1"S of a Binary Vector of Length N
Using 'Fread' to Import CSV File from an Archive into 'R' Without Extracting to Disk
Why Are Lubridate Functions So Slow When Compared with As.Posixct
Ggplot2: How to Adjust Fill Colour in a Boxplot (And Change Legend Text)
How to Test If Object Is a Vector
Passing a 'Data.Table' to C++ Functions Using 'Rcpp' And/Or 'Rcpparmadillo'
How to Add a Non-Overlapping Legend to Associate Colors with Categories in Pairs()
Ggplot2 Each Group Consists of Only One Observation
Merging Data Frames with Different Number of Rows and Different Columns
Geom_Rect Failure: Error in Eval(Expr, Envir, Enclos):Object 'Variable' Not Found
How to Insert Pictures into Each Individual Bar in a Ggplot Graph
How to Check If a Vector Contains N Consecutive Numbers
R Pheatmap: Change Annotation Colors and Prevent Graphics Window from Popping Up
How to Rotate the Axis Labels in Ggplot2
Different Results with Randomforest() and Caret's Randomforest (Method = "Rf")
How to Better Create Stacked Bar Graphs with Multiple Variables from Ggplot2