【发布时间】:2018-01-03 00:14:13
【问题描述】:
我想创建一个闪亮的应用程序,该应用程序具有用于编写某些 R 函数或命令的输入,通过 ui.R 读取它,然后将其传递给执行该 R 命令以显示结果的 server.R。
我花了几个小时搜索一些示例但找不到任何东西,我已经知道如何使用 ui 和服务器创建闪亮的应用程序并将输入值传递给服务器并使用它们,但我不知道是否有可能创建一个像 R 一样闪亮的应用程序,您可以在其中编写命令并返回结果,任何示例或帮助将不胜感激。
【问题讨论】:
我想创建一个闪亮的应用程序,该应用程序具有用于编写某些 R 函数或命令的输入,通过 ui.R 读取它,然后将其传递给执行该 R 命令以显示结果的 server.R。
我花了几个小时搜索一些示例但找不到任何东西,我已经知道如何使用 ui 和服务器创建闪亮的应用程序并将输入值传递给服务器并使用它们,但我不知道是否有可能创建一个像 R 一样闪亮的应用程序,您可以在其中编写命令并返回结果,任何示例或帮助将不胜感激。
【问题讨论】:
让用户在您的应用中运行代码是一种不好的做法,因为这会带来很大的安全风险。但是,对于开发,您可能需要检查 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())
【讨论】:
print("This is definitely not JS code!"),然后检查您的控制台。 alert 是来自 shinyjs 包的 R 函数。希望这会有所帮助!
我能够找到不需要shinyjs 的替代解决方案——想重申弗洛里安的担忧,即让用户在您的 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)
【讨论】: