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

前端 未结 4 1190
没有蜡笔的小新
没有蜡笔的小新 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:38

    I figured out a function that plugs the numbers from the matrix into the correct LaTeX code. In the code block where you use it you need results='asis' to get the LaTeX to render, and you can wrap the function in writeLines along with the other parts you need.

    I'm still open to more elegant solutions.

    ```{r}
    A <- matrix(c(1, 3, 0, 1), 2, 2)
    B <- matrix(c(5, 3, 1, 4), 2, 2)
    
    # Utility function to print matrices in proper LaTeX format
    print_mat <- function(mat) {
      n <- nrow(mat)
      c('\\begin{bmatrix}',
        paste0(sapply(seq_len(n - 1),
                      function(i) paste0(mat[i, ], collapse = ' & ')),
               ' \\\\'),
        paste0(mat[n, ], collapse = ' & '),
        '\\end{bmatrix}')
    } 
    
    ```
    
    ```{r, results = 'asis'}
    writeLines(c('$$',
                 print_mat(A),
                 '\\times',
                 print_mat(B),
                 '$$'))
    ```
    

提交回复
热议问题