I have a rmd document where I have the following
```{r code_block, echo=FALSE}
A = matrix(c(1,3,0,1),2,2)
B = matrix(c(5,3,1,4),2,2)
```
$$
\begin{bmatrix}
1 & 0 \\
3 & 1 \\
\end{bmatrix}
*
\begin{bmatrix}
5 & 1 \\
3 & 4 \\
\end{bmatrix}
$$
Now I would like to instead of hard coding the LaTeX part manually, I could use the matrix from the variables A and B instead. How could this be done?
Thanks.
If you prefer to use the console by default for all your R Markdown documents (restoring the behavior in previous versions of RStudio), you can make Chunk Output in Console the default: Tools -> Options -> R Markdown -> Show output inline for all R Markdown documents .
To open a new file, click File > New File > R Markdown in the RStudio menu bar. A window will pop up that helps you build the YAML frontmatter for the . Rmd file. Use the radio buttons to select the specific type of output that you wish to build.
In fact, you can take any R script and compile it into a report that includes commentary, source code, and script output. Reports can be compiled to any output format including HTML, PDF, MS Word, and Markdown.
Go to the Files tab in RStudio (lower right). Click Upload and browse to select the file you created. Then, use the read. csv() function to read in the file.
Straightforwardly, you can write latex line. writeLines()
or cat()
would be helpful.
You can use apply(A, 1)
with two step paste()
.
paste(collpase = "&")
: collapse each rowpaste(, "\\\\")
: collapse every column with \\
Then we can get the latex
formula of matrix.
write_matex <- function(x) {
begin <- "$$\\begin{bmatrix}"
end <- "\\end{bmatrix}$$"
X <-
apply(x, 1, function(x) {
paste(
paste(x, collapse = "&"),
"\\\\"
)
})
writeLines(c(begin, X, end))
}
If you conduct this function, write_matex(A)
gives
$$\begin{bmatrix}
1&0 \\
3&1 \\
\end{bmatrix}$$
When you use chunk option {r, results = 'asis'}
, you might see the matrix in both pdf and html.
Based on this function, you might freely use matrix in latex block. For this, $$
should be removed in the function. Instead of writeLines()
, paste(collapse = "")
can be used.
write_matex2 <- function(x) {
begin <- "\\begin{bmatrix}"
end <- "\\end{bmatrix}"
X <-
apply(x, 1, function(x) {
paste(
paste(x, collapse = "&"),
"\\\\"
)
})
paste(c(begin, X, end), collapse = "")
}
In the text part, you can implement this function as
$$
`r write_matex2(A)` \times `r write_matex2(B)`
$$
In r markdown
, this r
with back quotation can attach your r function and variable. So you can get
As you can see, this is reproducible.
(C <- matrix(1:10, nrow = 2))
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 1 3 5 7 9
#> [2,] 2 4 6 8 10
Similarly,
$$`r write_matex2(C)` + `r write_matex2(C)`$$
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With