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

青春壹個敷衍的年華 提交于 2021-01-27 06:03:00

问题


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.


回答1:


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())



回答2:


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)


来源:https://stackoverflow.com/questions/45347852/how-to-run-user-input-as-r-code-in-a-shiny-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!