[Tex/LaTex] How tonsert into Latex a Text File whose name is a variable

r

I need to insert a text file into LaTeX. But text file names are different for different projects. So I want to define text file name as a variable and refer to the variable when inserting the text

I tried the code as below. But

\VerbatimInput[baselinestretch=1,fontsize=\footnotesize]{{\myfile}}

doesn't work. Only

\VerbatimInput[baselinestretch=1,fontsize=\footnotesize]{abc.txt} 

Could anyone give me some guide?

\usepackage{fancyvrb}
<<text, echo=F>>=
targetvar<-'abc'
textfile<-paste(targetvar,'.txt',sep='') 
@
\newcommand{\myfile}{\Sexpr{textfile}}
\VerbatimInput[baselinestretch=1,fontsize=\footnotesize]{{\myfile}}

Best Answer

You can use Sweave's results=tex code chunk argument to construct a LaTeX \input{} directive that will insert the text from whatever file path R constructed.

This Sweave file (call it "example.Rnw") ...

\documentclass{article}
\usepackage{fancyvrb}
\begin{document}

<<text, echo=FALSE, results=tex>>=
targetvar<-'abc'
textfile <- paste(targetvar,'.txt',sep='')

cat("\\VerbatimInput[baselinestretch=1,fontsize=\\footnotesize]{",
    textfile,
    "}", sep="")
cat("\n")
@

\end{document}

... will produce this LaTex file ("example.tex") after being run through Sweave by a call to Sweave("example.Rnw"):

\documentclass{article}
\usepackage{fancyvrb}

\begin{document}

\VerbatimInput[baselinestretch=1,fontsize=\footnotesize]{abc.txt}

\end{document}