2017-07-19 58 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'里面看起来有些不对劲。 –

相关问题