I am an instructor looking to make a homework assignment and homework solution guide from the same Rmarkdown file by changing a document parameter I created called sol
I was able to build off this answer to make something that doesn't use a latex package (though I'm generating HTML slides, so that might be why this works).
Where you want the commenting out to begin, just add:
`r if(params$soln) {""}`
This didn't require me editing any of the thus-contained code blocks for conditional execution or anything else like that. Hope this helps someone!