R闪亮保存到服务器 [英] R Shiny Save to Server

查看:12
本文介绍了R闪亮保存到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个R闪亮的应用程序,该应用程序充当我的团队构建的模拟模型的GUI。用户定义参数,单击Run,模型将生成一系列图表和表格作为输出。我的问题是,每次用户打开应用程序时,他们都必须再次输入参数。我希望他们能够保存参数,并在返回应用程序时再次调出参数。

我最初的方法是让用户使用downloadHandler将CSV中的参数下载到他们的本地计算机,然后在他们的下一个会话中上传它们。这是不可行的,因为存在格式混乱或用户更改文件的风险太大,然后他们再次上载文件时我会出错。

我认为最有意义的是将参数保存在服务器上的一个文件中(我更喜欢.Rdata文件,这样我就可以将参数保存在列表中),并使用selectInput小部件来允许用户调用他们想要的参数文件。我不知道如何从闪亮的应用程序中保存到服务器,也不知道如何让downloadHandler执行此操作。

编辑 例如,当我这样做时: UI:

downloadLink("saveParams",label="Save Your Model")

服务器:

 output$saveParams <- downloadHandler(
    filename <- function(){
      paste0(input$nameModel,".RData")
    },

    content = function(file) {
      inputparams<-inputparams()
      save(inputparams, file = file)
    }
  )

它为用户提供了将文件保存到何处的选项,这是我想要避免的。我想让它自动放到服务器上。我尝试使用actionButton触发使用save的反应,但无法使其运行。 有什么建议吗?

推荐答案

这里是一个工作示例,使用textInputactionButton保存,使用selectInput加载文件。请注意,/home/user是您的闪亮应用程序拥有写入权限的文件夹。您可能需要更复杂的验证来确保用户输入有效的文件名。

如果您的闪亮应用有多个用户,您还需要找到一种方法来确保一个用户不会覆盖另一个用户保存的文件(例如,前缀为用户名,后缀为当前时间等),但这超出了本问题的范围。

ui.R

library(shiny)

shinyUI(fluidPage(

  # Application title
  titlePanel("Old Faithful Geyser Data"),

  # Sidebar with a slider input for number of bins
  sidebarLayout(
    sidebarPanel(
      sliderInput("bins",
                  "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30),
      textInput("save_file", "Save to file:", value="sample.RData"),
      actionButton("save", "Save input value to file"),
      uiOutput("load")
    ),

    # Show a plot of the generated distribution
    mainPanel(
      plotOutput("distPlot")
    )
  )
))

server.R

library(shiny)

shinyServer(function(input, output, session) {
  # render a selectInput with all RData files in the specified folder
  output$load <- renderUI({
    choices <- list.files("/home/user", pattern="*.RData")
    selectInput("input_file", "Select input file", choices)
  })
  # Save input$bins when click the button
  observeEvent(input$save, {
    validate(
      need(input$save_file != "", message="Please enter a valid filename")
    )
    bins <- input$bins
    save(bins, file=paste0("/home/user/", input$save_file))
    choices <- list.files("/home/user", pattern="*.RData")
    updateSelectInput(session, "input_file", choices=choices)
  })
  # Load an RData file and update input
  observeEvent(input$input_file, {
    load(paste0("/home/user/",input$input_file))
    updateSliderInput(session, "bins", value=bins)
  })

  output$distPlot <- renderPlot({

    # generate bins based on input$bins from ui.R
    x    <- faithful[, 2]
    bins <- seq(min(x), max(x), length.out = input$bins + 1)

    # draw the histogram with the specified number of bins
    hist(x, breaks = bins, col = 'darkgray', border = 'white')

  })

})

这篇关于R闪亮保存到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆