Несколько файлов Ввод на navbarPage Shiny - PullRequest
0 голосов
/ 02 февраля 2019

У меня есть код с navbarPage, который пользователь выбирает, какой тест он хочет, загружает свой файл, выбирает параметры и загружает результаты.

Моя проблема: как мне организовать свой код, чтобы знать, какойпротестировать выбранного пользователя?Чтобы мой код работал, как он просил?

Когда у меня был только один fileInput, мой код работал правильно, но когда я добавил второй, перестал показывать мои данные в виде таблицы на главной странице, и моя кнопка download сошла с ума.

Мой код:

ui <- navbarPage(title = "DadosFacil", fluid = TRUE, theme = shinytheme("cosmo"),

           #---- TABA DE NORMALIDADE       
           tabPanel("Normalidade", id = "NormalTab",
                    sidebarLayout(
                      sidebarPanel( 
                        helper("",
                               colour = "black",
                               type = "inline",
                               title = "Upload do arquivo",
                               size = "s",
                               content = "Selecione apenas um arquivo em documento de texto (.txt), para mais informacoes sobre como organizar seu arquivo acesse nosso faq."),

                        fileInput("file1", "Escolha seus dados em .txt", #Ill only accept .txt files
                                  accept =".txt"),


                        helper("",
                               colour = "black",
                               type = "inline",
                               title = "Ajuda",
                               size = "s",
                               content = "Marque se seu arquivo possui os nomes das variaveis na primeira linha"),

                        checkboxInput("header", "Header",value = TRUE),

                        helper("",
                               colour = "black",
                               type = "inline",
                               title = "Separador Decimal",
                               size = "s",
                               content = "Selecione como voce separou seus numeros no seu arquivo, comumente no Brasil se utiliza a virgula, nos outros paises o ponto. Note que caso selecione errado, obtera um erro."),

                        radioButtons("decimal", "Ponto ou Virgula: ",
                                     choices = c(Virgula = ",", Ponto = "."),
                                     selected = ","),

                        tags$hr(), #Linha horizontal

                        downloadButton("downloadData", "Download")
                        ),
                      mainPanel(
                        dataTableOutput("Previa")
                      )
                    )
                   ),

           #---ABA DA ANOVA
           navbarMenu("ANOVA",

             #---DELINEAMENTO INTEIRAMEINTE CASUALIZADO      
             tabPanel("DIC", id = "DicTab",
                      sidebarLayout(
                        sidebarPanel(
                          helper("",
                                 colour = "black",
                                 type = "inline",
                                 title = "Upload do arquivo",
                                 size = "s",
                                 content = "Selecione apenas um arquivo em documento de texto (.txt), para mais informacoes sobre como organizar seu arquivo acesse nosso faq."),

                          fileInput("file2", "Escolha seus dados em .txt -> DIC", #Ill only accept .txt files
                                    accept =".txt"),


                          helper("",
                                 colour = "black",
                                 type = "inline",
                                 title = "Ajuda",
                                 size = "s",
                                 content = "Marque se seu arquivo possui os nomes das variaveis na primeira linha"),

                          checkboxInput("header", "Header",value = TRUE),

                          helper("",
                                 colour = "black",
                                 type = "inline",
                                 title = "Separador Decimal",
                                 size = "s",
                                 content = "Selecione como voce separou seus numeros no seu arquivo, comumente no Brasil se utiliza a virgula, nos outros paises o ponto. Note que caso selecione errado, obtera um erro."),

                          radioButtons("decimal", "Ponto ou Virgula: ",
                                       choices = c(Virgula = ",", Ponto = "."),
                                       selected = ","),

                          tags$hr(), #Linha horizontal

                          downloadButton("downloadData", "Download")
                        ),
                        mainPanel(
                          dataTableOutput("Previa")
                      )
                      )
             ),

             tabPanel("DBC",
                      sidebarLayout(
                        sidebarPanel(

                        ),
                        mainPanel(

                        )
                      )
             ),

             tabPanel("DQL",
                      sidebarLayout(
                        sidebarPanel(

                        ),
                        mainPanel(

                        )
                      )

             )

           )
)

server <- function(input, output, session) {

  observe_helpers()

  datasetInputNormal <-reactive({
    req(input$file1)

    tryCatch({
      df <- read.table(input$file1$datapath,
                       header = input$header,
                       sep = "\t",
                       dec = input$decimal)
    },
    error = function(e){
      #Retorna error se der algum problema
      stop(safeError(e))
    })

    return(df)

  })

  datasetInputDic <-reactive({
    req(input$file2)

    tryCatch({
      df <- read.table(input$file2$datapath,
                       header = input$header,
                       sep = "\t",
                       dec = input$decimal)
    },
    error = function(e){
      #Retorna error se der algum problema
      stop(safeError(e))
    })

    return(df)

  })

  output$Previa <- DT::renderDataTable(DT::datatable(datasetInput()))

  output$NormalidadeDownload <- downloadHandler(
    filename = function(){
      paste("Resul_",input$file1$name, sep = "")
    },
    content = function(file){
      if(input$id == "NormalTab"){
        writeLines(VariosNormal(datasetInputNormal()), con = file, sep = "" ) #Call my function VariosNormal()
      } else if(input$id == "DicTab"){
        writeLines(Teste_DIC(datasetInputDic()), con = file, sep = "" ) #Call my function Teste_DIC()
      }

    }
  )
}

shinyApp(ui, server)

1 Ответ

0 голосов
/ 02 февраля 2019

Я наконец понял, как это исправить.Читая этот вопрос: R Блестящий файлВведите несколько типов файлов .Я заметил, что у меня не может быть двух выходов с одинаковым идентификатором, поэтому я создал еще один вывод для всего с отличающимся идентификатором и работал!Но мой вопрос: есть ли способ это исправить?Потому что в моем приложении у меня будет более 20 вкладок, каждая с его кнопками set os, единственный способ - получить такой большой код?

Мой код исправлен:

ui <- navbarPage(title = "DadosFacil", fluid = TRUE, theme = shinytheme("cosmo"),

           #---- TABA DE NORMALIDADE       
           tabPanel("Normalidade", id = "NormalTab",
                    sidebarLayout(
                      sidebarPanel( 
                        helper("",
                               colour = "black",
                               type = "inline",
                               title = "Upload do arquivo",
                               size = "s",
                               content = "Selecione apenas um arquivo em documento de texto (.txt), para mais informacoes sobre como organizar seu arquivo acesse nosso faq."),

                        fileInput("fileNormal", "Escolha seus dados em .txt", #Ill only accept .txt files
                                  accept =".txt"),


                        helper("",
                               colour = "black",
                               type = "inline",
                               title = "Ajuda",
                               size = "s",
                               content = "Marque se seu arquivo possui os nomes das variaveis na primeira linha"),

                        checkboxInput("headerNormal", "Header",value = TRUE),

                        helper("",
                               colour = "black",
                               type = "inline",
                               title = "Separador Decimal",
                               size = "s",
                               content = "Selecione como voce separou seus numeros no seu arquivo, comumente no Brasil se utiliza a virgula, nos outros paises o ponto. Note que caso selecione errado, obtera um erro."),

                        radioButtons("decimalNormal", "Ponto ou Virgula: ",
                                     choices = c(Virgula = ",", Ponto = "."),
                                     selected = ","),

                        tags$hr(), #Linha horizontal

                        downloadButton("downloadNormal", "Download")
                        ),
                      mainPanel(
                        dataTableOutput("PreviaNormal")
                      )
                    )
                   ),

           #---ABA DA ANOVA
           navbarMenu("ANOVA",

             #---DELINEAMENTO INTEIRAMEINTE CASUALIZADO      
             tabPanel("DIC", id = "DicTab",
                      sidebarLayout(
                        sidebarPanel(
                          helper("",
                                 colour = "black",
                                 type = "inline",
                                 title = "Upload do arquivo",
                                 size = "s",
                                 content = "Selecione apenas um arquivo em documento de texto (.txt), para mais informacoes sobre como organizar seu arquivo acesse nosso faq."),

                          fileInput("fileDic", "Escolha seus dados em .txt -> DIC", #Ill only accept .txt files
                                    accept =".txt"),


                          helper("",
                                 colour = "black",
                                 type = "inline",
                                 title = "Ajuda",
                                 size = "s",
                                 content = "Marque se seu arquivo possui os nomes das variaveis na primeira linha"),

                          checkboxInput("headerDic", "Header",value = TRUE),

                          helper("",
                                 colour = "black",
                                 type = "inline",
                                 title = "Separador Decimal",
                                 size = "s",
                                 content = "Selecione como voce separou seus numeros no seu arquivo, comumente no Brasil se utiliza a virgula, nos outros paises o ponto. Note que caso selecione errado, obtera um erro."),

                          radioButtons("decimalDic", "Ponto ou Virgula: ",
                                       choices = c(Virgula = ",", Ponto = "."),
                                       selected = ","),

                          tags$hr(), #Linha horizontal

                          downloadButton("downloadDic", "Download")
                        ),
                        mainPanel(
                          dataTableOutput("PreviaDic")
                      )
                      )
             ),

             tabPanel("DBC",
                      sidebarLayout(
                        sidebarPanel(

                        ),
                        mainPanel(

                        )
                      )
             ),

             tabPanel("DQL",
                      sidebarLayout(
                        sidebarPanel(

                        ),
                        mainPanel(

                        )
                      )

             )

           )
)

server <- function(input, output, session) {

  observe_helpers()

  #--- NORMAL TAB
  datasetInputNormal <-reactive({
    req(input$fileNormal)

    tryCatch({
      df <- read.table(input$fileNormal$datapath,
                       header = input$headerNormal,
                       sep = "\t",
                       dec = input$decimalNormal)
    },
    error = function(e){
      #Retorna error se der algum problema
      stop(safeError(e))
    })

    return(df)

  })


  output$PreviaNormal <- DT::renderDataTable(DT::datatable(datasetInputNormal()))

  output$downloadNormal <- downloadHandler(
    filename = function(){
      paste("Resul_Normal",input$fileNormal$name, sep = "")
    },
    content = function(file){
      writeLines(VariosNormal(datasetInputNormal()), con = file, sep = "" ) #Call my function VariosNormal()

    }
  )

  #---DIC TAB

  datasetInputDic <-reactive({
    req(input$fileDic)

    tryCatch({
      df <- read.table(input$fileDic$datapath,
                       header = input$headerDic,
                       sep = "\t",
                       dec = input$decimalDic)
    },
    error = function(e){
      #Retorna error se der algum problema
      stop(safeError(e))
    })

    return(df)

  })

  output$PreviaDic <- DT::renderDataTable(DT::datatable(datasetInputDic()))

  output$downloadDic <- downloadHandler(
    filename = function(){
      paste("Resul_Dic",input$fileDic$name, sep = "")
    },
    content = function(file){
      writeLines(Teste_DIC(datasetInputDic()), con = file, sep = "" ) #Call my function Teste_Dic

    }
  )

}

shinyApp(ui, server)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...