The question asks for a way to have the user interactively select an item from a list inside an RNW document (the same applies for other files that are knitted, like RMD):
%mydocument.Rnw
\documentclass{article}
\begin{document}
<<>>=
letterIndex <- menu(LETTERS, graphics = TRUE, title = "Select your favorite letter")
sprintf("My favorite letter is '%s'.", LETTERS[letterIndex])
@
\end{document}
This throws an error when the document is knitted using the "Compile PDF" button in Rstudio because menu
needs an interactive R session but "Compile PDF" starts a new, non-interactive session to process the document.
Error in menu(LETTERS, graphics = TRUE, title = "Select your favorite letter")
: menu()
cannot be used non-interactively
To solve this issue, the "Compile PDF" button must be avoided. Instead the document can be knitted calling knit
/knit2pdf
. Note that this may have some unexpected side-effects, see here to get an idea about this.
knit2pdf("mydocument.Rnw")
works (which I didn't expect when writing that comment). The menu of choices pops up in the middle of the knitting process. Nevertheless, I would prefer a solution that separates knitting and user interaction (as suggested in the comment):
#control.R
letterIndex <- menu(LETTERS, graphics = TRUE, title = "Select your favorite letter")
knit2pdf("mydocument2.Rnw")
%mydocument2.Rnw
\documentclass{article}
\begin{document}
<<>>=
sprintf("My favorite letter is '%s'.", LETTERS[letterIndex])
@
\end{document}
Here, the user interaction takes place before the document is knitted. The result letterIndex
is saved in the global environment and the knitting process reads it from there.
In both cases, instead of opening the RNW file and clicking "Compile PDF", the user now opens an R script containing knit2pdf
(and possibly the menu
call) and clicks "Source". This should not increase the difficulty level too much.