This was annoying me, so I decided to dig into it a bit more after I got back to my computer. My take on it is that the showEqn()
in matlib
is fundamentally broken, which I'll explain after I tell you how to just do what you want to do.
So, first, what you want to do is wrap an R code chunk in an equation environment and set results = "asis"
and echo = FALSE
. Here is the content of a minimally working Rmd file which will do what you want.
---
output: pdf_document
---
```{r matlib}
library(matlib)
A <- matrix(c(1, 2, -1, 2), 2, 2)
b <- c(2,1)
```
\begin{equation}
```{r, results = "asis", echo = FALSE}
showEqn(A, b, latex = TRUE)
```
\end{equation}
Now, the reason why I think showEqn()
is fundamentally broken is because the function itself dumps the LaTeX code straight into the io stream with cat()
. Side effects like this are best avoided and the choice of when and how to output to the stream are best left to the user. You can "fix" this with the capture.output()
. Below is a simple example of how it works.
x <- 1:3
cat_fun <- function(x) {
cat("Hello!")
x
}
y <- cat_fun(x)
#> Hello!
y
#> [1] 1 2 3
z <- capture.output(x)
z
#> [1] "[1] 1 2 3"
Created on 2020-09-03 by the reprex package (v0.3.0)
Now, to see how this can be used with showEqn()
here is a slightly different Rmd file.
---
output: pdf_document
---
```{r}
library(matlib)
A <- matrix(c(2, 1, -1,
-3, -1, 2,
-2, 1, 2), 3, 3, byrow=TRUE)
b <- c(8, -11, -3)
out <- paste(capture.output(showEqn(A, b, latex = TRUE)), collapse = "")
```
This allows us to save the output in an R object and use it anywhere else we want.
$`r out`$
$$`r out`$$
And we also now have the freedom to manipulate the output,
```{r}
new_out <- gsub("array", "bmatrix", out)
new_out <- gsub("\\{[lrc]+\\}", "\\{\\}", new_out)
```
$$`r new_out`$$
Now, I don't know _why_ you would want or need to do this,
but you _can_ when you eliminate the side-effects of the function.