在Shiny应用程序中如何将用户输入作为R代码运行?

6
我希望创建一个闪亮的应用程序,其中有一个输入框可以编写一些R函数或命令。通过ui.R读取它,然后将其传递给server.R执行该R命令以显示结果。
我花了几个小时搜索示例,但找不到任何东西。我已经知道如何使用ui和server创建Shiny应用程序,并将输入值传递到server并处理它们,但我不知道是否可以创建像R那样的闪亮应用程序,您可以编写命令并返回结果。任何示例或帮助都将不胜感激。
2个回答

8
让用户在您的应用程序中运行代码是不良做法,因为它存在巨大的安全风险。但是,在开发过程中,您可能想要检查Dean Attali的shinyjs软件包中的this function
链接中的示例:
  library(shiny)
  library(shinyjs)

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

一些例子说明在部署应用时包含它并不是一个好主意:
尝试输入以下内容:
shinyjs::alert(ls(globalenv()))

或者

shinyjs::alert(list.files())

谢谢Florian,这非常有帮助,但只适用于JavaScript代码吗?我能用它来编写R代码吗? - Programmer Man
它仅适用于R代码。尝试输入 print("This is definitely not JS code!"),并检查您的控制台。alert是来自shinyjs包的R函数。希望这可以帮助! - Florian

4

我能够找到一种不需要使用shinyjs的替代方案--想再次强调Florian的担忧:通常让用户在你的Shiny应用程序中运行代码并不是一件好事(不安全)。以下是替代方案:

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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接