1

I have written a for loop in LaTeX using the forloop package, and on each iteration, I would like to use a different subset of a vector that is defined in an R chunk above. However, each iteration of the loop resets the counter back to its starting value before the code within the loop. Below is an example:

```{r}
n <- 3
count <- 1
vec <- c("A","B","C")
```
\newcounter{i}

\forloop{i}{0}{\value{i} < `n`}{

```{r}
print(vec[count])
```

```{r}
count <- count + 1
```
}

I desire A B C as my output, but instead, the counter is reset and I get A A A.

Is there a way to define the R variable as global and prevent it from resetting upon the next iteration, or is there a way to use the LaTeK counter in the R chunk?

Thank you!

0

1 Answer 1

1

The code of R is not sensitive to LaTeX or markdown context.

All the R chunks are evaluated first and changed by the R outputs before of the LaTeX export and compilation, so LaTeX or markdown syntax cannot influence in any way the R code. Only it can change the result, for instance it can change the subset showed in cursive, but not change the range of the subset. Therefore, the loop must be in the R side.

On the other hand, you do not need at all loop to show a subset of some vector. Example:

---
output:
  pdf_document: default
---

```{r, comment="",echo=FALSE}
vec <- c("A","B","C","D","E")
```

My interest is in the *`r vec[2:4]` part*.

This should produce:

My interest is in the B, C, D part.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .