I don't have a sure solution. First, just a note that I asked a similar question some time ago (but doesn't answer your case).
Then, is the material to display text or image? I think you could get a switch mechanism as described here, the idea is that you'd need some kind of placeholder. For text you could try a text the same length but in white (as implemented in the CTAN package hideanswer, or if you're using a monospace font, a series of spaces the same length so that people can't copy-paste the hidden text), and for images you could create placeholder images of the same size.
For example some code that halfway works (but would take some effort to make it fully work well):
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
soln <- TRUE
fill_with_spaces <- function(char){
rep(" ", nchar(char)) |>
paste0(collapse = "")
}
make_blank <- function(expr){
res <- capture.output(eval(expr))
res <- sapply(res, fill_with_spaces)
names(res) <- sapply(names(res), fill_with_spaces)
res
}
conditional_display <- function(expr, soln){
expr <- substitute(expr)
if(soln){
eval(expr)
} else{
make_blank(expr)
}
}
```
## Slide with R Output
```{r cars, echo = TRUE}
conditional_display(summary(cars), soln)
cat("some text")
```