# How can I get R and Tikz to cooperate in a loop?

I'm using knitr and compiling my .Rnw file in Rstudio. Here's a MWE illustrating my issue. I want the code below to output "1, 2, 3" but instead it gives me "1, 1, 1".

%%%%%%%%%%%%%%%%
\documentclass[border=20pt]{standalone}
\usepackage{tikz}
\begin{document}

<<eval=TRUE, echo=FALSE, results='hide'>>=
faux.data<-c(1,2,3)
i<-1    # set loop index to 1
@

\begin{tikzpicture}
\foreach \x in {1,2,3}
{\node[draw, circle] at (\x,0) {\Sexpr{faux.data[i]}};

<<eval=TRUE, echo=FALSE, results='hide'>>=
@
}

\end{tikzpicture}
\end{document}
%%%%%%%%%%%%%%%%%


• Welcome to TeX.SE! Oct 8, 2021 at 13:03
• It might be {\node[draw, circle] at (\x,0) {\Sexpr{toLatex(faux.data[i])}};. See Is there any alternative to \Sexpr{} to write a matrix object in R?
– Ross
Oct 8, 2021 at 14:30
• Thanks for the suggestion, Ross. If I update index i in an R chunk outside the TeX loop, then \Sexpr{faux.data[i]} returns the correct entry from the vector faux.data. This makes me think that the properties of \Sexpr{} are not the issue. Oct 8, 2021 at 15:44