6

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.

Florian
  • 24,425
  • 4
  • 49
  • 80
Programmer Man
  • 1,314
  • 1
  • 9
  • 29

2 Answers2

8

Letting users run code in your app is bad practice, since it comes with great security risks. However, for development you might want to check this function from the shinyjs package by Dean Attali.

Example from the link:

  library(shiny)
  library(shinyjs)

  shinyApp(
    ui = fluidPage(
      useShinyjs(),  # Set up shinyjs
      runcodeUI(code = "shinyjs::alert('Hello!')")
    ),
    server = function(input, output) {
      runcodeServer()
    }
  )

Some examples of why it is not such a good idea to include when deploying your app:

Try the input:

shinyjs::alert(ls(globalenv()))

or

shinyjs::alert(list.files())
Florian
  • 24,425
  • 4
  • 49
  • 80
  • Thank you Florian this is very helpful, but only for javascript code? can i use it for R code? – Programmer Man Jul 27 '17 at 10:27
  • It works for R code only. Try typing `print("This is definitely not JS code!")`, and check your console. `alert` is an R function from the shinyjs package. Hope this helps! – Florian Jul 27 '17 at 10:28
3

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)
mysteRious
  • 4,102
  • 2
  • 16
  • 36