You may want to inform yourself about human rights in China.

On Exporting Complex Matrices From R to LaTeX via Xtable

tags: computing R
date: 2023-06-14
update: 2023-06-15

The xtable (pdf) R package generates \(\LaTeX\) code for tables, in particular for matrices. However, exporting a complex (as in \(\mathbb{C}\)) matrix fails (mind the boilerplate, which strips the default, full-blown table display):

library("xtable")

sigma_y  <- matrix(c(0, 1i, -1i, 0), 2, 2)

m <- xtable(
	sigma_y,
	align=rep("",ncol(sigma_y)+1))

digits(m) <- xdigits(m)

print(m,
	floating = FALSE, tabular.environment = "pmatrix",
	hline.after=NULL, include.rownames=FALSE, include.colnames=FALSE
)
Error in x < 0 : invalid comparison with complex values
Calls: print -> print.xtable -> do.call -> formatC -> pmax

Here’s a quick workaround, inspired by a solution from this stackoverflow post:

library("xtable")

xtable <- function(x, ...) {
	if (class(x[[1]]) == "complex") {
		z <- sapply(x, function(y) {
			if (y == 0)     return(as.character(0))
			if (Im(y) == 0) return(as.character(Re(y)))

			t <- ""
			if (Re(y) != 0) t <- as.character(Re(y))

			if (Im(y) == 1) {
				if (Re(y) == 0) t <- "i"
				else            t <- paste(t, "+i")
			} else if (Im(y) == -1)
				t <- paste(t, "-i")
			else {
				if (Re(y) == 0)     t <- paste(Im(y), "i")
				else if (Im(y) > 0) t <- paste(t, "+", Im(y), "i")
				else                t <- paste(t, Im(y), "i")
			}
			return(t)
		})
		dim(z) <- dim(x)
		xtable::xtable(z, ...)
	} else
		xtable::xtable(x, ...)
}

sigma_y  <- matrix(c(0, 1i, -1i, 0), 2, 2)

m <- xtable(
	sigma_y,
	align=rep("",ncol(sigma_y)+1))

digits(m) <- xdigits(m)

print(m,
	floating = FALSE, tabular.environment = "pmatrix",
	hline.after=NULL, include.rownames=FALSE, include.colnames=FALSE
)
% latex table generated in R 4.3.0 by xtable 1.8-4 package
% Thu Jun 15 01:48:46 2023
\begin{pmatrix}{}
  0 &  -i \\
   i & 0 \\
  \end{pmatrix}

Note: You’ll need something more involved if you have a genuine table, not a vector, containing complex numbers. Refer to the aforementioned stackoverflow post for more.


Comments

By email, at mathieu.bivert chez:

email