R-Shiny: выбор ввода реактивного при вводе файла - PullRequest
0 голосов
/ 16 марта 2020

Я очень новичок в Shiny и не уверен, что делаю это дистанционно правильно / полностью упрощенно. Я пытаюсь получить заголовки столбцов из Excel fileInput в раскрывающемся списке selectInput. Поэтому, по сути, я бы хотел, чтобы параметры поля выбора определялись заголовками ввода файла. Затем он будет ссылаться на мое уравнение на сервере, который будет выполнять вычисления на основе набора данных в столбце (бит на сервере с вводом $ col). Я ценю любые комментарии / ответы, спасибо

РЕДАКТИРОВАТЬ: думаю, мне нужно использовать uiOutput и renderUI ??

ui

 ui <- fluidPage(theme = shinytheme(),

setBackgroundColor("white"),

titlePanel(img(src = "image.png", height = 125, width = 450)),

(h1("review app", style = "color:#337ab7")),
p("Calculate"),

headerPanel(h3("Input data here", style = "color:#337ab7")), 


sidebarLayout(
sidebarPanel( position =c("left"),  style = "color:#337ab7", 
    numericInput("SL",
                "SL", 1, min=1, max=10),

    numericInput("LT", "LT",0, min=0, max = 52),
    fileInput("file1", 'choose file',
              accept = c(".xlsx") ),
    selectInput("col", "Column", choices = unique(colnames(input$file1)
                                                   )),

   checkboxInput("smooth", "Clean my data", value = FALSE, width = NULL),

    actionButton("action_Calc", label = "Refresh & Calculate", icon("redo"), 
         style="color: #fff; background-color: #337ab7; border-color: #2e6da4"), 
     ),


mainPanel(
    tabsetPanel(
      tabPanel("SS", h1(textOutput("SS"), style = "color:#337ab7")),
      tabPanel("guide",  img(src = "guide.png", height = 200, width = 600)),
      tabPanel("Mydata", div(tableOutput('contents'), style="font-size:55%"))
          ))))

сервер

 server <- function(input, output) {


  Data <- reactive({
  req(input$file1)
  inFile <- input$file1
  read_excel(inFile$datapath, 1)
})

output$contents <- renderTable(bordered = TRUE, style= "border-color:#337ab7", hover = TRUE, {
  Data()
})


values<- reactiveValues()
observe({
    input$action_Calc
    values$int<- isolate({ if (input$smooth) (round( input$SL*sqrt(input$LT/4)*sd( tsclean(Data()[[input$col]], 
       replace.missing = TRUE, lambda = NULL)) , digits= 2))
       else (round( input$SL*sqrt(input$LT/4)*sd(Data()[[input$col]]), digits = 2)) })})

    output$SS <- renderText({paste("Calculated is", values$int)} )

} sparkApp (пользовательский интерфейс, сервер)

1 Ответ

0 голосов
/ 16 марта 2020

updatedSelectInput должен сделать это за вас. Ниже приведен минимальный пример.

Чтобы уменьшить зависимости пакетов, я переключился на загрузку .csv, а не .xlsx. Обратите внимание, что загруженный файл не проверен, поэтому, если мусор поступит, вы получите мусор.

library(shiny)

#UI
ui <- fluidPage(

    selectInput('mydropdown', label = 'Select', choices = 'No choices here yet'),

    fileInput('myfileinput', label = 'Select File', accept = c(".csv"))

)

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

    observeEvent(input$myfileinput, {

        mytable <- read.csv(input$myfileinput$datapath)

        updateSelectInput(session, "mydropdown", label = "Select", choices = colnames(mytable))

    })

}

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