Learn R Programming

matlib (version 1.0.0)

latexMatrix: Create and Manipulate LaTeX Representations of Matrices

Description

The purpose of the latexMatrix() function is to facilitate the preparation of LaTeX and Markdown documents that include matrices. The function generates the the LaTeX code for matrices of various types programmatically. The objects produced by the function can also be manipulated, e.g., with standard arithmetic functions and operators: See latexMatrixOperations.

The latexMatrix() function can construct the LaTeX code for a symbolic matrix, whose elements are a symbol, with row and column subscripts. For example:


 \begin{pmatrix}
   x_{11}  & x_{12}  & \dots  & x_{1m}  \
   x_{21}  & x_{22}  & \dots  & x_{2m}  \
   \vdots & \vdots & \ddots & \vdots \
   x_{n1}  & x_{n2}  & \dots  & x_{nm}
 \end{pmatrix}
 

When rendered in LaTeX, this produces: $$ \begin{pmatrix} x_{11} & x_{12} & \cdots & x_{1m} \\ x_{21} & x_{22} & \cdots & x_{2m} \\ \vdots & \vdots & & \vdots \\ x_{n1} & x_{n2} & \cdots & x_{nm} \\ \end{pmatrix} $$

Alternatively, instead of characters, the number of rows and/or columns can be integers, generating a matrix of given size.

As well, instead of a character for the matrix symbol, you can supply a matrix of arbitrary character strings (in LaTeX notation) or numbers, and these will be used as the elements of the matrix.

You can print the resulting LaTeX code to the console. When the result is assigned to a variable, you can send it to the clipboard using write_clip(). Perhaps most convenient of all, the function can be used used in a markdown chunk in a Rmd or qmd document, e.g,


```{r results = "asis"}
latexMatrix("\lambda", nrow=2, ncol=2,
               diag=TRUE)
```

This generates $$ \begin{pmatrix} \lambda_{1} & 0 \\ 0 & \lambda_{2} \\ \end{pmatrix} $$

Usage

latexMatrix(
  symbol = "x",
  nrow = "n",
  ncol = "m",
  rownames = NULL,
  colnames = NULL,
  matrix = getOption("latexMatrixEnv"),
  diag = FALSE,
  sparse = FALSE,
  zero.based = c(FALSE, FALSE),
  end.at = c("n - 1", "m - 1"),
  comma = any(zero.based),
  exponent,
  transpose = FALSE,
  show.size = FALSE,
  digits = getOption("digits") - 2,
  fractions = FALSE,
  prefix = "",
  suffix = "",
  prefix.row = "",
  prefix.col = ""
)

partition(x, ...)

# S3 method for latexMatrix partition(x, rows, columns, ...)

getLatex(x, ...)

# S3 method for latexMatrix getLatex(x, ...)

getBody(x, ...)

# S3 method for latexMatrix getBody(x, ...)

getWrapper(x, ...)

# S3 method for latexMatrix getWrapper(x, ...)

Dim(x, ...)

# S3 method for latexMatrix Dim(x, ...)

Nrow(x, ...)

# S3 method for latexMatrix Nrow(x, ...)

Ncol(x, ...)

# S3 method for latexMatrix Ncol(x, ...)

# S3 method for latexMatrix print( x, onConsole = TRUE, bordermatrix = getOption("bordermatrix"), cell.spacing = getOption("cell.spacing"), colname.spacing = getOption("colname.spacing"), ... )

# S3 method for latexMatrix is.numeric(x)

# S3 method for latexMatrix as.double(x, locals = list(), ...)

# S3 method for latexMatrix [(x, i, j, ..., drop)

# S3 method for latexMatrix cbind(..., deparse.level)

# S3 method for latexMatrix rbind(..., deparse.level)

# S3 method for latexMatrix dimnames(x)

Dimnames(x) <- value

# S3 method for latexMatrix Dimnames(x) <- value

Rownames(x) <- value

# S3 method for latexMatrix Rownames(x) <- value

Colnames(x) <- value

# S3 method for latexMatrix Colnames(x) <- value

Value

latexMatrix() returns an object of class "latexMatrix"

which contains the LaTeX representation of the matrix as a character string, in the returned object are named:

  • "matrix" (the LaTeX representation of the matrix);

  • "dim" (nrow and ncol);

  • "body" (a character matrix of LaTeX expressions for the cells of the matrix);

  • "wrapper"(the beginning and ending lines for the LaTeX matrix environment).

partition(), rbind(), cbind(), and indexing of

"latexMatrix" objects also return a "latexMatrix" object.

Arguments

symbol

name for matrix elements, character string. For LaTeX symbols, the backslash must be doubled because it is an escape character in R. That is, you must use symbol = "\\beta" to get \(\beta\). Alternatively, this can be an R matrix object, containing numbers or LaTeX code for the elements. For a row or column vector, use matrix(..., nrow=1) or matrix(..., ncol=1)

nrow

Number of rows, a single character representing rows symbolically, or an integer, generating that many rows.

ncol

Number of columns, a single character representing columns symbolically, or an integer, generating that many columns.

rownames

optional vector of names for the matrix rows. if symbol is an R matrix with row names, these are used. For a matrix with a non-numeric (e.g., "m") number of rows, 3 names should be supplied, for the 1st, 2nd, and last rows.

colnames

optional vector of names for the matrix columns. if symbol is an R matrix with column names, these are used. For a matrix with a non-numeric (e.g., "n") number of columns, 3 names should be supplied, for the 1st, 2nd, and last columns.

matrix

Character string giving the LaTeX matrix environment used in \begin{}, \end{}. Typically one of:

"pmatrix"

uses parentheses: "(", ")"

"bmatrix"

uses square brackets: "[", "]"

"Bmatrix"

uses braces: "{", "}"

"vmatrix"

uses vertical bars: "|", "|"

"Vmatrix"

uses double vertical bars: "||", "||"

"matrix"

generates a plain matrix without delimiters

"smallmatrix"

same as "matrix", but for in-line use

Small matrix definitions from the mathtools LaTeX package are also possible for in-line use (e.g., "psmallmatrix"). The default is taken from the "latexMatrixEnv" option; if this option isn't set, then "pmatrix" is used.

diag

logical; if TRUE, off-diagonal elements are all 0 (and nrow must == ncol)

sparse

logical; if TRUE replace 0's with empty characters to print a sparse matrix

zero.based

logical 2-vector; start the row and/or column indices at 0 rather than 1; the default is c(FALSE, FALSE)

end.at

if row or column indices start at 0, should they end at n - 1 and m - 1 or at n and m? (where n and m represent the characters used to denote the number of rows and columns, respectively); the default is c("n - 1", "m - 1"); applies only when nrow or ncol are characters

comma

logical; if TRUE, commas are inserted between row and column subscripts, as in x_{1,1}; the default is FALSE except for zero-based indices.

exponent

if specified, e.g., "-1", or "1/2", the exponent is applied to the matrix

transpose

if TRUE, the transpose symbol "\top" is appended to the matrix; this may also be a character string, e.g., "T", "\prime", "\textsf{T}" are commonly used.

show.size

logical; if TRUE shows the order of the matrix as an appended subscript.

digits

for a numeric matrix, number of digits to display;

fractions

logical; if TRUE, try to express non-integers as rational numbers, using the fractions function.

prefix

optional character string to be pre-pended to each matrix element, e.g, to wrap each element in a function like "\sqrt" (but add braces)

suffix

optional character string to be appended to each matrix element, e.g., for exponents on each element

prefix.row

optional character string to be pre-pended to each matrix row index

prefix.col

optional character string to be pre-pended to each matrix column index

x

a "latexMatrix" object

...

for rbind() and cbind(), one or more "latexMatrix" objects with, respectively, the same number of columns or rows; otherwise, for compatibility with generic functions, may be ignored

rows

row numbers after which partition lines should be drawn in the LaTeX printed representation of the matrix; if omitted, then the matrix isn't partitioned by rows

columns

column numbers after which partition lines should be drawn in the LaTeX printed representation of the matrix; if omitted, then the matrix isn't partitioned by columns

onConsole

if TRUE, the default, print the LaTeX code for the matrix on the R console.

bordermatrix

if TRUE, the LaTeX "\bordermatrix" macro is used for matrices with row and/or column names. This macro doesn't work in Markdown-based documents. The default is taken from the "bordermatrix" option, and if that option isn't set the argument is set to FALSE.

cell.spacing

a character whose width is used to try to even out spacing of printed cell elements; the default is taken from the "cell.spacing" option, and if that option isn't set the character "e" is used.

colname.spacing

a character whose width is used to try to even out spacing of printed column names; the default is taken from the "colname.spacing" option, and if that option isn't set the character "i" is used.

locals

an optional list or named numeric vector of variables to be given specific numeric values; e.g., locals = list(a = 1, b = 5, c = -1, d = 4) or locals = c(a = 1, b = 5, c = -1, d = 4)

i

row index or indices (negative indices to omit rows)

j

column index or indices (negative indices to omit columns)

drop

to match the generic indexing function, ignored

deparse.level

to match the generic rbind() and cbind() functions; ignored

value

for "Dimnames<-()", a two-element list with, respectively, character vectors of row and column names; for "Rownames<-()" and "Colnames<-()", a vector of names.

Author

John Fox

Details

This implementation assumes that the LaTeX amsmath package will be available because it uses the shorthands \begin{pmatrix}, ... rather than


\left(
  \begin{array}(ccc)
  ...
  \end{array}
\right)

You may need to use extra_dependencies: ["amsmath"] in your YAML header of a Rmd or qmd file.

You can supply a numeric matrix as the symbol, but the result will not be pretty unless the elements are integers or are rounded. For a LaTeX representation of general numeric matrices, use matrix2latex.

The partition() function modifies (only) the printed LaTeX representation of a "latexMatrix" object to include partition lines by rows and/or columns.

The accessor functions getLatex(), getBody(), getWrapper(), getDim(), getNrow(), and getNcol() may be used to retrieve components of the returned object.

Various functions and operators for "latexMatrix" objects are documented separately; see, latexMatrixOperations.

See Also

latexMatrixOperations, matrix2latex, write_clip

Examples

Run this code
latexMatrix()

# return value
mat <- latexMatrix()
str(mat)
cat(getLatex(mat))

# copy to clipboard (can't be done in non-interactive mode)
if (FALSE) {
clipr::write_clip(mat) 
} 

# can use a complex symbol
latexMatrix("\\widehat{\\beta}", 2, 4)

# numeric rows/cols
latexMatrix(ncol=3)
latexMatrix(nrow=4)
latexMatrix(nrow=4, ncol=4)

# diagonal matrices
latexMatrix(nrow=3, ncol=3, diag=TRUE)
latexMatrix(nrow="n", ncol="n", diag=TRUE)
latexMatrix(nrow="n", ncol="n", diag=TRUE, sparse=TRUE)

# commas, exponents, transpose
latexMatrix("\\beta", comma=TRUE, exponent="-1")
latexMatrix("\\beta", comma=TRUE, transpose=TRUE)
latexMatrix("\\beta", comma=TRUE, exponent="-1", transpose=TRUE)

# for a row/column vector, wrap in matrix()
latexMatrix(matrix(LETTERS[1:4], nrow=1))
latexMatrix(matrix(LETTERS[1:4], ncol=1))

# represent the SVD, X = U D V'  symbolically
X <- latexMatrix("x", "n", "p")
U <- latexMatrix("u", "n", "k")
D <- latexMatrix("\\lambda", "k", "k", diag=TRUE)
V <- latexMatrix("v", "k", "p", transpose = TRUE)
cat("\\mathrm{SVD:}\n", getLatex(X), "=\n", getLatex(U),
    getLatex(D), getLatex(V))

# supply a matrix for 'symbol'
m <- matrix(c(
  "\\alpha", "\\beta",
  "\\gamma", "\\delta",
  "\\epsilon", "\\pi",
  0 , 0), 4, 2, byrow=TRUE)
latexMatrix(m)

# Identity matrix
latexMatrix(diag(3))
latexMatrix(diag(3), sparse=TRUE)

# prefix / suffix
latexMatrix(prefix="\\sqrt{", suffix="}")
latexMatrix(suffix="^{1/2}")

# show size (order) of a matrix
latexMatrix(show.size=TRUE)
latexMatrix(nrow=3, ncol=4, show.size=TRUE)

# handling fractions
m <- matrix(3/(1:9), 3, 3)
latexMatrix(m)
latexMatrix(m, digits=2)
latexMatrix(m, fractions=TRUE)

# zero-based indexing
latexMatrix(zero.based=c(TRUE, TRUE))

# partitioned matrix
X <- latexMatrix(nrow=5, ncol=6)
partition(X, rows=c(2, 4), columns=c(3, 5))

# binding rows and columns; indexing
X <- latexMatrix("x", nrow=4, ncol=2)
Y <- latexMatrix("y", nrow=4, ncol=1)
Z <- latexMatrix(matrix(1:8, 4, 2))
cbind(X, Y, Z)
rbind(X, Z)
X[1:2, ]
X[-(1:2), ]
X[1:2, 2]

# defining row and column names
W <- latexMatrix(rownames=c("\\alpha_1", "\\alpha_2", "\\alpha_m"),
                 colnames=c("\\beta_1", "\\beta_2", "\\beta_n"))
W
Rownames(W) <- c("\\mathrm{Abe}", "\\mathrm{Barry}", "\\mathrm{Zelda}")
Colnames(W) <- c("\\mathrm{Age}", "\\mathrm{BMI}", "\\mathrm{Waist}")
W

Run the code above in your browser using DataLab