【问题标题】:Dynamic Input Selector Based on Uploaded Data基于上传数据的动态输入选择器
【发布时间】:2015-03-23 02:03:44
【问题描述】:

提前感谢您的帮助。我了解如何根据预定义数据集的其他输入来操作动态输入。 即加载汽车数据集。用户选择单选按钮表示他们只想查看蓝色汽车。这会更改 UI 上某些输入选择器中的选项。

但是,如果我想允许用户上传 csv 文件,我该如何动态更新所有相关的小部件。 即用户上传他们的数据,输入选择器显示数据集中的所有变量用于绘图和回归。

斜体部分是我的麻烦。

ui.r

library(shiny)

# Define UI for application that draws a histogram
shinyUI(fluidPage(

  titlePanel("My R Shiny App"),

  sidebarPanel(
    fileInput('file', 'Choose file to upload.'),
    #Select Box: y
    selectInput("y_input", label = h5("Select Time Series/Response Variable"),
                choices = names(myData),
                selected = NULL)

  )
) 
)

server.r

library(shiny)

#Run once when app is launched
#Load data

shinyServer(function(input, output) {

  #Run once each time a user visits the app
  #Put code to build a distinct set of reactive objects for user


  output$Variable_Selector <- renderUI({
    if(is.null(input$file))
      return(NULL)
    inFile <- input$file
    myData <- read.csv(inFile$datapath)
    if (is.null(myData))
      return(NULL)
  })
})

global.r

myData = NULL

谢谢!

【问题讨论】:

    标签: r shiny shiny-server


    【解决方案1】:

    这是使用函数 observeupdateSelectInput 的一种解决方案 - 对您的代码进行了一些其他小的修改。为了演示,我制作了以下两个具有不同列名的 csv 文件:

    Df1 <- data.frame(
      x=1:5,
      y=2*(1:5),
      z=3*(1:5))
    ##
    Df2 <- data.frame(
      a=6:10,
      b=2*(6:10),
      c=3*(6:10),
      d=letters[1:5],
      stringsAsFactors=F)
    ##
    write.csv(Df1,file="~/tempfiles/Df1.csv",row.names=F)
    ##
    write.csv(Df2,file="~/tempfiles/Df2.csv",row.names=F)
    

    ui.R

    library(shiny)
    
    shinyUI(fluidPage(
    
      titlePanel("My R Shiny App"),
    
      sidebarPanel(
    
        fileInput(
          'file', 
          'Choose file to upload.'
        ),
    
        selectInput(
          "y_input", 
          label = h5("Select Time Series/Response Variable"),
          ""
        )
    
      )
    
    ))
    

    server.R

    library(shiny)
    
    shinyServer(function(input, output, session) {
    
      inFile <- reactive({
        if (is.null(input$file)) {
          return(NULL)
        } else {
          input$file
        }
      })
    
      myData <- reactive({
        if (is.null(inFile())) {
          return(NULL)
        } else {
          read.csv(inFile()$datapath)
        }
      })
    
      observe({
        updateSelectInput(
          session,
          "y_input",
          choices=names(myData()))
    
      })
    
    })
    

    global.R

    myData <- NULL
    

    下面是几张截图,展示了 UI 如何根据上传的文件发生变化:

    【讨论】:

    • 非常感谢@nrussel。你能提供一个关于观察和会话的链接吗?
    • 不客气,observesession
    猜你喜欢
    • 2019-04-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2016-04-01
    • 2021-12-29
    • 2011-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多