How to input external file in figure caption with tufte-latex?

With the tufte-handout class, I want to insert some text in a figure caption, from an external text file generated with R.

\documentclass[a4paper]{tufte-handout}
\newcommand\nlikely{\input{myvariable.txt}}
\begin{document}

N Likely = \nlikely

\begin{figure*}[h]
\centering
\includegraphics[width=\textwidth]{amce-likely.pdf}
\caption{N Likely = \nlikely}
\label{fig:amce-likely}
\end{figure*}

\end{document}


I can use the command \nlikely without any problem in the text, but when I try to use it in the figure caption I get an error:

Argument of \@iiminipage has an extra }


What's baffling me is that when I define \nlikely manually at the beginning of the document, no problem:

\newcommand\nlikely{190}


Is there a proper way to do this? Is \input inserting weird stuff that breaks the caption?

Welcome! I had to fiddle a bit to reproduce the error. I hope I got an appropriate example in the end.

If so, you just need a \protect:

\documentclass[a4paper]{tufte-handout}
\usepackage[demo]{graphicx}
\newcommand\nlikely{\input{myvariable.txt}}
\begin{document}

N Likely = \nlikely

\begin{figure*}[h]
\centering
\includegraphics[width=\textwidth]{amce-likely.pdf}
\caption{N Likely = \protect\nlikely}
\label{fig:amce-likely}
\end{figure*}

\end{document}


• Thank you! This is great. I didn't know about the \protect command. Works like a charm. – Erispoe Aug 7 '15 at 23:45
• @Erispoe You're welcome! You often see it in commands writing stuff to the .toc file. Useful command to know about - you don't need it much, but when you do, it resolves lots of mysterious frustrating errors. – cfr Aug 8 '15 at 0:02