首页 > 解决方案 > 保存用户定义的变量并在 Shiny 中运行 R scipt

问题描述

我有一个闪亮的应用程序,可以全局保存一些变量。我希望用户能够单击“运行”按钮,这将 1)全局保存变量,2)运行使用这些变量的 R 脚本。

下面是我所在的位置,但在点击按钮之前我无法保存变量。

library(shiny)

ui <- fluidPage(
      
column(4, wellPanel(dateInput('date', label = 'Date input: yyyy-mm-dd', value = Sys.Date()))),
column(4, wellPanel(numericInput('STD', 'STD', 1.2))),
  
actionButton("Run", "Run the tool")

)

server <- function(input, output) {
  
  observeEvent(input$STD, {
    STDShiny <<- input$STD1
  })

  observeEvent(input$date, {
    dateShiny <<- input$date
  })
  
  observeEvent(input$Run, {
    source("someScript.R")
  })
}

示例脚本:someScript.R

dir.create(paste(date,STD, sep = ''))

任何帮助表示赞赏。

标签: rshiny

解决方案


Somescript.R 代码:

dir.create(paste(.GlobalEnv$dateShiny, .GlobalEnv$STDShiny, sep = ''))

新亚普:

library(shiny)
library(tidyverse)

ui <- fluidPage(
    
    column(4, wellPanel(dateInput('date', label = 'Date input: yyyy-mm-dd', value = Sys.Date()))),
    column(4, wellPanel(numericInput('STD', 'STD', 1.2))),
    
    actionButton("Run", "Run the tool") #The button to trigger script
    
)

server <- function(input, output) {
 
 #Upon clicking in the button the following code gets executed  
 observeEvent(input$Run,{
     
        #declare as variables in the global env with the values of the inputs
        walk2(c('STDShiny', 'dateShiny'), c(input$STD, input$date), ~{
            assign(..1, ..2, envir = .GlobalEnv)
        })
    
        #Run the script
        exec(source, file = 'someScript.R')

})}


shinyApp(ui, server)

推荐阅读