2016-09-15 26 views
1

我有一個帶有滑塊輸入的Shiny應用程序,我想根據用戶上傳的數據集中的最大值爲滑塊設置最大可能值。最大距離將根據上傳的數據集而變化。根據無功輸出值設置最大sliderInput值

這是我正在嘗試做的最低工作示例。下面我只是硬編碼號爲maxdistance,但在我的代碼它的計算方法:

library(shiny) 

ui <- fluidPage(
    sliderInput("range_one", "Core:", min = 0, max = textOutput("maxdistance"), value = c(0,0)) 
) 

server <- function(input,output) { 
    output$maxdistance <- renderText({ 
    maxdistance <- 250 
    return(maxdistance) 
    }) 
} 

shinyApp(ui=ui,server=server) 

我收到以下錯誤:

Error in max - min : non-numeric argument to binary operator 

這是有道理的,因爲我是要求一個文本輸出,那麼我怎麼才能得到這個輸出作爲sliderInput()函數中使用的數字值?

+0

只需使用'updateSliderInput'來更新服務器端的滑塊。 –

+0

您能否發佈一個如何正確執行此操作的示例?我嘗試了一些基於幫助的東西,但它導致應用程序崩潰。 – user29609

回答

1

這裏是一個例子。

library(shiny) 

ui <- shinyUI(fluidPage(

    titlePanel("Example"), 

    sidebarLayout(
    sidebarPanel(
     sliderInput("bins", 
        "Number of bins:", 
        min = 1, 
        max = 50, 
        value = 30), 
     actionButton("change", "Change slider max value") 
    ), 

    mainPanel(
     plotOutput("distPlot") 
    ) 
) 
)) 

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

    observeEvent(input$change, { 
    max = sample(50:100, 1) 
    updateSliderInput(session, "bins", max=max) 
    }) 

    output$distPlot <- renderPlot({ 
    x <- faithful[, 2] 
    bins <- seq(min(x), max(x), length.out = input$bins + 1) 

    hist(x, breaks = bins, col = 'darkgray', border = 'white') 
    }) 
}) 

shinyApp(ui = ui, server = server) 
+0

謝謝!我能夠根據你的答案做出一個有效的例子,但是現在我的問題是試圖從observe()函數中的反應函數中訪問我的計算值。我可以對它進行硬編碼,例如max = 250,或者使用max = sample(50:100,1),但我似乎無法訪問存儲在數據框中的計算數據。我試過:數據< - 數據(),最大=最大(數據$距離),但它給出的錯誤:連接重置由同伴和崩潰的應用程序。 – user29609

+0

沒有完整的代碼很難說清楚。 –

+0

呵呵,似乎動作按鈕是必要的。如果我添加它,它不會崩潰。我認爲應用程序崩潰是因爲它依賴於上傳的數據來獲取最大值,所以我們需要保持默認值直到數據上傳,然後單擊更改滑塊最大值。非常感謝! – user29609

1

更改如下,它會工作:

sliderInput("range_one", "Core:", 
      min = 0, max = as.integer(textOutput("maxdistance")), 
      value = c(0,0)) 
+0

謝謝,但是這給出了錯誤:findStepSize(min,max,step)(list)對象中的錯誤不能被強制鍵入'integer' – user29609

+0

您是否使用完全相同的代碼來更新此行?這個對我有用。你正在從renderText返回maxdistance(這是一個整數初始化爲250)嗎? –

+0

是的,不知道爲什麼它不適用於我。 – user29609

0

這裏是我使用在服務器端實現我原來的問題的預期結果的代碼,而無需操作按鈕:

observe({ 
infile <- input$file # user input file upload 
if(!is.null(infile)) { 
    processed <- processed() # list of processed elements returned from earlier reactive({}) function with my app 
    processed_data <- processed$processed_data # get the processed data from the list and save as data frame 
    maxdistance <- max(processed_data$distance) # calculate the max distance from the processed data 
    updateSliderInput(session, "range_one", max=maxdistance) # update the slider called "range_one" based on the maxdistance 
    } 

})

這允許應用程序使用默認最大滑塊值UNT上傳一個文件。用戶上傳文件後,會處理數據並更新滑塊。

相關問題