updateSelectInput适用于data.frame,但不适用于dataframe

时间:2017-04-24 08:44:53

标签: r shiny

我想更新一个交互式rmarkdown闪亮文档中的selectInput取决于数据框列表中的选择,但闪亮给我这个错误。警告:[[:尝试在get1index中选择少于一个元素

时出错

实施例。更改输入$ disp取决于所选的cyl。

示例1.创建一个由cyl分割的3个data.frame列表,并按名称选择一个。

    ---
title: "Test observe"
output: html_document
runtime: shiny
---



    ```{r echo=FALSE}

    datos <- mtcars
    datos <- split(datos, datos$cyl )
    un_cyl <- unique(mtcars$cyl)
    gears <- c(3,4,5)
    disp_list <- unique(mtcars$disp)


    inputPanel(
     selectInput("cyl", label = "cyl",
                  choices = un_cyl),
      selectInput("disp", label = "disp",
                  choices = disp_list,  selected = disp_list[1])
    )


    eventos_sel <- reactive({
      eventos <- datos[[input$cyl]]
      eventos
    })


    elegibles <- reactive({
      tmp <- eventos_sel()
      tmp <- unique(tmp$disp)
      return(tmp)
    })

    # hacer un updateSelectInput

    observe({
      updateSelectInput(session, inputId = "disp", choices = elegibles())
      })


    renderPrint(elegibles())


    ```

示例2.与示例1相同,但使用原始data.frame的子集而不是创建列表。这个例子有效但我需要一个数据帧列表。

---
title: "Test observe"
output: html_document
runtime: shiny
---



```{r echo=FALSE}

datos <- mtcars
# change from example 1 
# datos <- split(datos, datos$cyl ) 
un_cyl <- unique(mtcars$cyl)
gears <- c(3,4,5)
disp_list <- unique(mtcars$disp)


inputPanel(
 selectInput("cyl", label = "cyl",
              choices = un_cyl),
  selectInput("disp", label = "disp",
              choices = disp_list,  selected = disp_list[1])
)


eventos_sel <- reactive({
  # change from example 1 
  eventos <- datos[datos$cyl == input$cyl, ]
  eventos
})


elegibles <- reactive({
  tmp <- eventos_sel()
  tmp <- unique(tmp$disp)
  return(tmp)
})

# hacer un updateSelectInput

observe({
  updateSelectInput(session, inputId = "disp", choices = elegibles())
  })


renderPrint(elegibles())


```

1 个答案:

答案 0 :(得分:0)

  1. 要引用列表中的特定数据框,您必须使用字符,而不是整数,即使它们的名称只是一个数字
  2. 你必须在使用它之前检查input$cyl是否有一个有效值,这样就不会出现错误(闪亮似乎在input$cyl具有有效值之前运行该函数)
  3. 工作代码......

    ---
    title: "Test observe"
    output: html_document
    runtime: shiny
    ---
    
    ```{r echo=FALSE}
    datos <- mtcars
    datos <- split(datos, datos$cyl)
    un_cyl <- unique(mtcars$cyl)
    gears <- c(3,4,5)
    disp_list <- unique(mtcars$disp)
    
    inputPanel(
      selectInput("cyl", label = "cyl",
                  choices = un_cyl),
      selectInput("disp", label = "disp",
                  choices = disp_list,  selected = disp_list[1])
    )
    
    eventos_sel <- reactive({
      cylname <- as.character(input$cyl)
      if (length(cylname) == 0) cylname <- "6"
      eventos <- datos[[cylname]]
    })
    
    elegibles <- reactive({
      tmp <- eventos_sel()
      tmp <- unique(tmp$disp)
      return(tmp)
    })
    
    # hacer un updateSelectInput
    observe({
      updateSelectInput(session, inputId = "disp", choices = elegibles())
    })
    
    renderPrint(elegibles())
    ```