基于上载数据的动态输入选择器

sba*_*ers 4 r shiny shiny-server

在此先感谢您的帮助.我理解如何根据预定义数据集的其他输入操作动态输入.即加载汽车数据集.用户选择单选按钮说他们只想看蓝色车.这会更改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)

  )
) 
)
Run Code Online (Sandbox Code Playgroud)

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)
  })
})
Run Code Online (Sandbox Code Playgroud)

global.r

myData = NULL
Run Code Online (Sandbox Code Playgroud)

谢谢!

nru*_*ell 7

下面是使用的一个功能的解决方案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)
Run Code Online (Sandbox Code Playgroud)

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"),
      ""
    )

  )

))
Run Code Online (Sandbox Code Playgroud)

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()))

  })

})
Run Code Online (Sandbox Code Playgroud)

global.R:

myData <- NULL
Run Code Online (Sandbox Code Playgroud)

以下是一些屏幕截图,显示了UI如何根据上传的文件进行更改:

正在上传<code> Df1.csv </ code>

正在上传<code> Df2.csv </ code>