Title: Use a vector from an R markdown code chunk in a LaTeX environment (pmatrix)?
Tags: r;latex;r-markdown
Question: I want to create a column vector in R markdown from a variable in a code chunk.  Namely, I want to use the ```\begin{pmatrix}``` environment.  But in LaTeX, each element of the vector is separated by a newline ```\\```.  The code in LaTeX would be as follows:

```\begin{pmatrix} x_1 \\ x_2 \\ x_3 \end{pmatrix}```.

I want it to produce the following:
column vector with parentheses
where x_1, x_2, and x_3 are the elements of a numeric vector in an R code chunk.

Is this possible?


Here is the accepted answer: You can  have R create the LaTeX code, and put it in a chunk with ```results = 'asis'```, or you can use inline R code:

```---
title: "Untitled"
author: "Gregor"
date: "December 5, 2018"
output: pdf_document
---

```{r echo = FALSE, results = 'asis'}
x = 1:3
cat("$$ \\begin{pmatrix}", paste(x, collapse = " \\\\ "), "\\end{pmatrix} $$", sep = " ")
```

Or inline code:

$$
\begin{pmatrix}
`r x[1]` \\ `r x[2]` \\ `r x[3]`
\end{pmatrix}
$$

Alternately

$$
\begin{pmatrix}
`r  paste(x, collapse = " \\\\ ")`
\end{pmatrix}
$$
```

Yielding:



If you're doing this a lot, you could easily make a little convenience function, possibly even a hook, depending how you want to use it.

Comment for this answer: Your third example is exactly what I was looking for—a method that easily generalizes to any size without additional code.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2018:00:12/05/18', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<r><latex><r-markdown>', 'Title': 'Use a vector from an R markdown code chunk in a LaTeX environment (pmatrix)?', 'ViewCount': 2035, 'id': 53640454, 'user_AboutMe': "<p>If I had it my way, I'd rock climb all day, do math all night, and sleep when I'm dead.</p>\n", 'user_AccountId': 8566943.0, 'user_DisplayName': 'GregDoesMath', 'user_Reputation': 39.0, 'user_Views': 6.0, 'user_id': 8456329.0}}