For R Markdown, How do I display a matrix from R variable

前端 未结 4 1102
没有蜡笔的小新
没有蜡笔的小新 2021-02-05 23:14

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          


        
4条回答
  •  星月不相逢
    2021-02-05 23:47

    Straightforwardly, you can write latex line. writeLines() or cat() would be helpful.

    You can use apply(A, 1) with two step paste().

    1. paste(collpase = "&"): collapse each row
    2. paste(, "\\\\"): 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.


    Latex block

    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)`$$
    

提交回复
热议问题