Convert R code/function to character output?

I like to put the R-code that produced a shiny thing (graph, table, whatever) below the thing itself. It's annoying however to maintain 2 bits of code that are essentially the same. Is there any way to...capture (?) some R code, or 🤷 something where I could get a text output for the shiny app. As an example:

output$graphGroup <- renderPlot({
  shinyAce::updateAceEditor(session, 
                            value = boxPlots_code(),
                            editorId = "boxCode_out" )
  boxPlots_create()
}) 

boxPlots_create <- reactive({
  thing1 <- as.numeric(input$thing1)
  thing2 <- as.logical(input$thing2)
  boxPlot <- plot_function(x, 
                           thing1, thing2)
  return(bioPlot)
})

boxPlots_code <- reactive({
  thing1 <- as.numeric(input$thing1)
  thing2 <- as.logical(input$thing2)
  boxPlotCode <- paste0(rCodeSetup(),'
boxPlot <- plot_function(x,
                         ', thing1,", ", thing2,")")
  return(boxPlotCode)
})

Ideally I'd like to take the "boxPlots_create" code and turn it into a single character. I've started messing with the "formals" function, and looking a bit at roxygen (because it kind of does a that type of stuff). Another option would be to make a source file for each chunk of shiny code, and either source that file, or grab the text. But, I wanted to check here first to see if I'm just missing some awesome R-function (be it base or some package I need to check out).

What you describe sounds similar to Shiny showcase mode
https://shiny.rstudio.com/articles/display-modes.html

Alternatively, you could probably write your function first time as character string, so you can easily display it. But also pass it to the parse() then to the eval() function to have it execute

Ahhh, that's a good idea! I don't really like the "showcase" mode because it shows EVERYTHING, and I'm just trying to get them to learn some more simple concepts.

heres a demo of two ways:

library(shiny)

ui <- fluidPage(
 
  fluidRow(
    textOutput("func_eval"),
    textOutput("func_def")
  ),
  fluidRow(
    textOutput("txtfunc_eval"),
    textOutput("txtfunc_def")
  )
)


server <- function(input, output) {
  
 myfunction <- function() {
    pointless_calc <- 75 * 123

    return(42)
  }

 txtfunc_def <- "myfunction <- function (){
        a <- 'HELLO'
                return (paste0(a, ' WORLD'))
            }"

  output$func_eval <- renderText({
    myfunction()
  })
  output$func_def <- renderText({
    capture.output(print.function(myfunction))
  })
  
  output$txtfunc_eval <- renderText({
    getfunc <- eval(parse(text = txtfunc_def))
    getfunc()
  })
  output$txtfunc_def <- renderText({
    txtfunc_def
  })
  
}

# Run the application
shinyApp(ui = ui, server = server)

I'm adjusting my code as we speak! Thanks a bunch.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.