How to run user input as R code in a Shiny app?

Viewed 1742

I want to create a shiny application that has an input for writing some R function or Command, reads it through the ui.R then passes it to the server.R that executes that R command to display the results.

I spent hours searching about some example but couldn't find anything, I already know how to create Shiny apps using ui and server and pass the input values to server and work with them, but I have no idea if it's possible to create a shiny app like R where you can write the commands and return the results, any example or help would be appreciated.

2 Answers

I was able to find an alternative solution that doesn't require shinyjs -- wanted to restate Florian's concern that in general it is not a good thing (not secure) to let users run code in your Shiny app. Here is the alternative:

library(shiny)
library(dplyr)

ui <- fluidPage(
   mainPanel(
      h3("Data (mtcars): "), verbatimTextOutput("displayData"),
      textInput("testcode", "Try filtering the dataset in different ways: ", 
           "mtcars %>% filter(cyl>6)", width="600px"), 
      h3("Results: "), verbatimTextOutput("codeResults"))
)

server <- function(input, output) {
    shinyEnv <- environment() 
    output$displayData <- renderPrint({ head(mtcars) })  # prepare head(mtcars) for display on the UI

    # create codeInput variable to capture what the user entered; store results to codeResults
    codeInput <- reactive({ input$testcode })
    output$codeResults <- renderPrint({
      eval(parse(text=codeInput()), envir=shinyEnv)
    })
}

shinyApp(ui, server)
Related