I usually collaborate with people who is not interested in the underlying code of analyses. So usually I hide the code. But I'd like to allow the user to see the code if they want.
I have tried:
{r, echo=FALSE}
inputPanel(
selectInput("ShowCode", label = "Do you want to see the code?",
choices = c("TRUE", "FALSE"), selected = "FALSE")
)
ShowC <- renderText({input$ShowCode})
ShowC
In the next code chunk I set as options:
{r, echo = ShowC}
#Whatevercode
The first chunk properly allows the user to choose TRUE or FALSE, the second one shows the code or not depending on the option selected by default, but doesn't change with the user choice.
Instead of using a chunk to display the code, you can display it in the Shiny app, in this way it is easy to show/hide with the help of ConditionalPanel
. To display a stylish code, you can use the monaco package, or aceEditor, or shinyAce. Here is an example with monaco:
---
title: "Untitled"
author: "Stéphane Laurent"
date: "2023-07-14"
output: html_document
runtime: shiny
---
To learn more, see [Interactive Documents](http://rmarkdown.rstudio.com/authoring_shiny.html).
```{r, include=FALSE}
library(shiny)
library(monaco)
code <- '
inputPanel(
selectInput("n_breaks", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 20),
sliderInput("bw_adjust", label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
renderPlot({
hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
xlab = "Duration (minutes)", main = "Geyser eruption duration")
dens <- density(faithful$eruptions, adjust = input$bw_adjust)
lines(dens, col = "blue")
})
'
```
```{r, echo=FALSE}
inputPanel(
checkboxInput("show", "Show code")
)
inputPanel(
conditionalPanel(
condition = "input.show",
monaco(
contents = code,
language = "r",
width = "800px", height = "400px"
)
)
)
inputPanel(
selectInput("n_breaks", label = "Number of bins:",
choices = c(10, 20, 35, 50), selected = 20),
sliderInput("bw_adjust", label = "Bandwidth adjustment:",
min = 0.2, max = 2, value = 1, step = 0.2)
)
renderPlot({
hist(faithful$eruptions, probability = TRUE, breaks = as.numeric(input$n_breaks),
xlab = "Duration (minutes)", main = "Geyser eruption duration")
dens <- density(faithful$eruptions, adjust = input$bw_adjust)
lines(dens, col = "blue")
})
```