Блестящий: отображать кнопки только после загрузки файла.

Я экспериментирую с Shiny, и мне это нравится. Я создал небольшое приложение, в котором студенты загружают файл csv, затем выбирают зависимые переменные и независимые переменные, а затем R вычисляет линейную регрессию. Работает нормально. Я загрузил его по адресу:

http://carlosq.shinyapps.io/Regresion

[Вы можете использовать этот файл, чтобы проверить его, если хотите. "пиво" является зависимой переменной, а остальные переменные, кроме "id", являются независимыми]

Вот server.R:

# server.R
library(shiny)

shinyServer(function(input, output) {

  filedata <- reactive({
    infile <- input$file1
    if (is.null(infile)){
      return(NULL)      
    }
    read.csv(infile$datapath)
  })

  output$dependent <- renderUI({
    df <- filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    selectInput("dependent","Select ONE variable as dependent variable from:",items)
  })


  output$independents <- renderUI({
    df <- filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    selectInput("independents","Select ONE or MANY independent variables from:",items,multiple=TRUE)
  })


  output$contents <- renderPrint({
    input$action
    isolate({   
      df <- filedata()
      if (is.null(df)) return(NULL)
      fmla <- as.formula(paste(input$dependent," ~ ",paste(input$independents,collapse="+")))
      summary(lm(fmla,data=df))
    })   
  })

}) 

А вот и ui.R:

# ui.R
library(shiny)

shinyUI(fluidPage(
  titlePanel("Multiple Linear Regression"),
  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Choose CSV File',
                accept=c('text/csv', 
                         'text/comma-separated-values,text/plain', 
                         '.csv')),

      tags$hr(),
      uiOutput("dependent"),
      uiOutput("independents"),
      tags$hr(),
      actionButton("action", "Press after reading file and selecting variables")

    ),
    mainPanel(
      verbatimTextOutput('contents')
    )
  )
))

Мой вопрос: я хочу, чтобы появление кнопки «Нажмите после прочтения файла и выбора переменных» зависело от успешной загрузки.

Я попытался использовать предложение, содержащееся здесь:

Сделать условную панель зависимой от файлов, загруженных с помощью fileInput

Но я просто не могу заставить это работать.

Я приветствую любую помощь.


person user23438    schedule 04.01.2015    source источник


Ответы (2)


Этот код работал у меня

ui.R

 # ui.R
library(shiny)

shinyUI(fluidPage(
  titlePanel("Multiple Linear Regression"),
  sidebarLayout(
    sidebarPanel(
      fileInput('file1', 'Choose CSV File',
                accept=c('text/csv', 
                         'text/comma-separated-values,text/plain', 
                         '.csv')),

      tags$hr(),
      uiOutput("dependent"),
      uiOutput("independents"),
      tags$hr(),
      uiOutput('ui.action') # instead of conditionalPanel
    ),
    mainPanel(
      verbatimTextOutput('contents')
    )
  )
))

server.R

# server.R
library(shiny)

shinyServer(function(input, output) {

  filedata <- reactive({
    infile <- input$file1
    if (is.null(infile)){
      return(NULL)      
    }
    read.csv(infile$datapath)
  })

  output$dependent <- renderUI({
    df <- filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    selectInput("dependent","Select ONE variable as dependent variable from:",items)
  })


  output$independents <- renderUI({
    df <- filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    selectInput("independents","Select ONE or MANY independent variables from:",items,multiple=TRUE)
  })


  output$contents <- renderPrint({
    input$action
    isolate({   
      df <- filedata()
      if (is.null(df)) return(NULL)
      fmla <- as.formula(paste(input$dependent," ~ ",paste(input$independents,collapse="+")))
      summary(lm(fmla,data=df))
    })   
  })


  output$ui.action <- renderUI({
    if (is.null(input$file1)) return()
    actionButton("action", "Press after reading file and selecting variables")
  })

}) 
person Marat Talipov    schedule 04.01.2015
comment
Спасибо, Марат. Я попробовал ваше решение. От этого кнопка исчезает ... и это хорошо. Но он не появляется после загрузки файла. Я считаю, что ваш файл server.R включает строку, которая проверяет, успешно ли загружен файл. - person user23438; 04.01.2015
comment
@ user23438, мне не удалось получить решение с помощью conditionPanel, потому что я не знал, как правильно настроить condition. Я отредактировал ответ, который теперь основан на uiOutput. - person Marat Talipov; 04.01.2015
comment
Еще раз спасибо, Марат, за уделенное время. Ваше новое решение приближает меня к решению. Теперь кнопка появляется в нужный момент, но это создает проблему с моим output $ contents. Раньше у меня был код в этом разделе, заключенный в изолированное ({}), которое было активировано input $ action. Теперь input $ action пропал, потому что больше нет кнопки. Я мог бы избавиться от изолята, но затем он печатает мусор, пока не будут выбраны правильные переменные. - person user23438; 05.01.2015
comment
Если вы хотите предотвратить преждевременный вывод в output $ contents, вы можете вставить туда пару проверок: замените input$action на if (is.null(input$action)) return() и if (input$action==0) return() - person Marat Talipov; 05.01.2015

Вот рабочий ShinyApp и финальная версия ui.R и server.R, основанная на всех предложениях Марата.

Сначала ui.R

# ui.R

library(shiny)

shinyUI(fluidPage(
  titlePanel("Multiple Linear Regression with R/Shiny"),
  sidebarLayout(
    sidebarPanel(
      p("Please upload a CSV formatted file with your data."),
      fileInput('file1', label='Click button below to select the file in your computer.',
                accept=c('text/csv', 
                         'text/comma-separated-values,text/plain', 
                         '.csv')),

      tags$hr(),
      uiOutput("dependent"),
      uiOutput("independents"),
      tags$hr(),
      uiOutput('ui.action') # instead of conditionalPanel
    ),
    mainPanel(
      p("Here's the output from your regression:"),
      verbatimTextOutput('contents')
    )
  )
))

и server.R

# server.R

library(shiny)

shinyServer(function(input, output) {

  filedata <- reactive({
    infile <- input$file1
    if (is.null(infile)){
      return(NULL)      
    }
    read.csv(infile$datapath)
  })

  output$ui.action <- renderUI({
    if (is.null(filedata())) return()
    actionButton("action", "Run regression")
  })

  output$dependent <- renderUI({
    df <- filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    selectInput("dependent","Now select ONE variable as dependent variable from:",items)
  })


  output$independents <- renderUI({
    df <- filedata()
    if (is.null(df)) return(NULL)
    items=names(df)
    names(items)=items
    selectInput("independents","Also select ONE or MANY independent variables in the box below. You can change your selection several times:",items,multiple=TRUE)
  })


  output$contents <- renderPrint({
    if (is.null(input$action)) return()
    if (input$action==0) return()
    isolate({
      df <- filedata()
      if (is.null(df)) return(NULL)
      fmla <- as.formula(paste(input$dependent," ~ ",paste(input$independents,collapse="+")))
      summary(lm(fmla,data=df))
    })
  })


}) 

Еще раз спасибо за помощь Марату.

person user23438    schedule 04.01.2015