2017-07-19 45 views
0

我想編寫一個讀取上載數據的應用程序,然後由於列中唯一元素的數量(列的名稱爲Big)而放置足夠多的numericInput。這個問題here幫助了我。有光澤的輸入窗口小部件的動態數量

的代碼如下:

library(shiny) 
ui <- fluidPage(
    fileInput(inputId = "up","", accept = '.csv'), 
    uiOutput("sliders") 
) 

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

    INPUT <- reactive({ 
    infile <- input$up 

    #validate(need(input$up, "Input a valid filepath."))  

    read.csv(infile$datapath, header = TRUE, sep = ",") 
    }) 

inVars <- reactive({ 
    unique(INPUT()$Big) 
    }) 

    output$sliders <- renderUI({ 
    pvars <- length(inVars()) 
    lapply(seq(pvars), function(i) { 
     numericInput(inputId = paste0("range", pvars[i]),label = pvars[i],value = 1) 
    }) 
    }) 

} 

shinyApp(ui = ui, server = server) 

三個問題:

當我把的validate

if (is.null(infile)) 
return(NULL) 

相反,它讓我看起來像一個錯誤這個:

missing value where TRUE/FALSE needed

我該怎麼做才能擺脫這個錯誤?

2.我怎麼能添加對numericInput的每一個標籤嗎?

3.我怎樣才能稍後使用輸入值?在reactive的環境?

感謝

回答

0

的問題是不是與if (is.null(infile))說法,它與lapply功能。當Shiny應用剛啓動時,整個server函數被執行,inVars()的長度爲0,而序列seq(pvars)將爲10。那麼numericInput將失敗,因爲當i等於0時,您正在參考pvars[i]

以下是修復問題並解答問題的代碼。

library(shiny) 
ui <- fluidPage(
    fileInput(inputId = "up","", accept = '.csv'), 
    uiOutput("sliders") 
) 

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

    INPUT <- reactive({ 
    infile <- input$up 
    if (is.null(infile)) 
     return(NULL) 
    read.csv(infile$datapath, header = TRUE, sep = ",") 
    }) 

inVars <- reactive({ 
    unique(INPUT()$Big) 
    }) 

    output$sliders <- renderUI({ 
    pvars <- length(inVars()) 
    if (pvars > 0) { 
     div(
     lapply(seq(pvars), function(i) { 
      numericInput(inputId = paste0("range", inVars()[i]),label = inVars()[i],value = 1) 
     }), 
     actionButton("getValues", "Get values"), 
     tableOutput('table') 
    ) 
    } 
    }) 

    values <- 0 

    # get the values of each numericInput and store them in "values" 
    observeEvent(input$getValues, { 
     # initialize vector 
     values <<- rep(NA, length(inVars())) 
     names(values) <<- inVars() 

     for(k in 1:length(inVars())) { 
     inputName <- paste0("range", inVars()[k]) 
     # only get a value if the numeric input exists 
     if (!is.null(inputName)) 
      values[[k]] <<- input[[inputName]] 
     } 
    # show values as a table 
    output$table <- renderTable(data.frame(
         variable = inVars(), 
         values)) 

    }) 

} 

shinyApp(ui = ui, server = server) 

更新:

測試代碼,使用.csv文件中包含的內容:

num,Big 
1,a 
2,a 
3,b 
4,b 
5,c 
6,c 
7,d 
8,d 

截圖:

Screenshot

+0

這不起作用。我在'ui'中添加了'dataTableOutput(「table」)',但仍然不起作用。另外,我想自動讀取沒有和動作按鈕的值。 –

+0

它應該與'tableOutput'一起工作,我更新了用於測試的輸入數據和屏幕截圖的答案,請檢查您是否擁有最新版本的Shiny。如果您想自動讀取值,可以在https://stackoverflow.com/a/40643541/4322318 – Geovany

+0

中查看解決方案。您的代碼存在一個問題,我無法弄清楚。如果你改變'd'的值,'c'的值將會改變。當我第一次使用不同的數據集運行你的代碼時,出現了一個錯誤:'參數意味着不同的行數:4,5。 'observeEvent'裏面看起來有些不對勁。 –

相關問題