Add \usepackage{comment}
to the preamble of your latex file.
At the line before the optional section starts, do
<<startcomment, results='asis', echo=FALSE>>=
if(!CreateOptionalSection){
cat("\\begin{comment}")
}
@
At the line after the optional section ends, do
<<endcomment, results='asis', echo=FALSE>>=
if(!CreateOptionalSection){
cat("\\end{comment}")
}
@