如果您想在运行应用程序后在全局环境中为用户提供数据框,您可以使用assign()。以下示例使用了可以添加为 add-in to RStudio 的闪亮小部件的逻辑:
shinyApp(
ui = fluidPage(
textInput("name","Name of data set"),
numericInput("n","Number observations", value = 10),
actionButton("done","Done")
),
server = function(input, output, session){
thedata <- reactive({
data.frame(V1 = rnorm(input$n),
V2 = rep("A",input$n))
})
observeEvent(input$done,{
assign(input$name, thedata(), .GlobalEnv)
stopApp()
})
}
)
请记住,当闪亮的应用程序运行时,您的 R 线程会持续执行,因此您只有在应用程序停止运行后才能访问全局环境。这就是带有闪亮界面的软件包的处理方式。
如果您希望用户能够在应用程序运行时使用该数据框,您可以使用例如shinyAce 添加代码编辑器。一个使用 shinyAce 执行任意代码的闪亮应用程序的简短示例:
library(shinyAce)
shinyApp(
ui = fluidPage(
numericInput("n","Number observations", value = 10),
aceEditor("code","# Example Code.\n str(thedata())\n#Use reactive expr!"),
actionButton("eval","Evaluate code"),
verbatimTextOutput("output")
),
server = function(input, output, session){
thedata <- reactive({
data.frame(V1 = rnorm(input$n),
V2 = rep("A",input$n))
})
output$output <- renderPrint({
input$eval
return(isolate(eval(parse(text=input$code))))
})
}
)
但是这个包附带了一些很好的例子,所以也看看那些。