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