marco
marco

Reputation: 73

How to make \Sexpr{} ignore NA

I run into the following issue. I define a Latex command for ifcase to choose from several options. Then I have some r code that determines the numbers used in ifcase via \Sexpr{}. My problem is that when \Sexpr produces NA those also appear in the output file. I hope that the MWE helps to clarify what I mean, otherwise please don't hesitate to ask.

\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}

\newcommand{\QPR}[1]
{
\ifcase #1
\or 
         A
\or
         B
\or
         C
\fi
}

<<g, echo=FALSE, results=tex,prefix=FALSE>>=
S=2:3
@

\QPR{\Sexpr{S[1]}}
\QPR{\Sexpr{S[2]}}
\QPR{\Sexpr{S[3]}}

\end{document}

The output reads "B C NA" but I only want "B C"

Upvotes: 0

Views: 63

Answers (1)

user2554330
user2554330

Reputation: 44867

The problem here is that \ifcase only allows an integer argument, and NA doesn't look like one to LaTeX. You need to change NA into some integer value that isn't in the list of cases. For example, this version converts NA to -1, which would never match a case:

\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}

\newcommand{\QPR}[1]
{
\ifcase #1
\or 
         A
\or
         B
\or
         C
\fi
}

<<g, echo=FALSE, results=tex,prefix=FALSE>>=
S=2:3
hideNA <- function(x) if (is.na(x)) -1 else x
@

\QPR{\Sexpr{hideNA(S[1])}}
\QPR{\Sexpr{hideNA(S[2])}}
\QPR{\Sexpr{hideNA(S[3])}}

\end{document}

Upvotes: 1

Related Questions