在Shiny中使用动态生成的列名称

时间:2018-05-13 17:15:03

标签: r shiny

我有一个Shiny应用,其中包含两个数据帧。 用户按下一个按钮,在数据框中创建新列

我还有一个selectInput框,我希望在Shiny应用程序中显示数据框列的名称(即如果用户按下了按钮,那么SlectInput框将包含新列名)。

到目前为止我的尝试:

---
title: "GUI"
output: html_document
runtime: shiny
---

```{r, echo=FALSE}
library(EndoMineR)
RV <- reactiveValues(data = mtcars)
shinyApp(

ui = fluidPage(
    selectInput("variable", "Variable:",
                colnames(RV$data)),
    tableOutput("data")
  ),
  server = function(input, output) {
    observeEvent(input$doExtractor, {
    mtcars$cyl2<-mtcars$cyl*10
  })
  }
)

```

但是我收到了错误:

Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

1 个答案:

答案 0 :(得分:0)

除了MLavoie已经提到过的内容之外,你还想使用updateSelectInput来做这样的事情。以下是工作示例。

shinyApp(

  ui = fluidPage(
    column(
      width = 3,
      selectInput(
        inputId = "variable", 
        label = "Variable:",
        choices =  colnames(mtcars)),
      actionButton(
        inputId = "doExtractor",
        label = "do Extractor"
      )
    ),
    column(
      width = 9,
      dataTableOutput("data")
    )
  ),
  server = function(input, output,session) {
    RV <- reactiveValues(data = mtcars)
    observeEvent(input$doExtractor, {
      browser()
      RV$data$cyl2<-mtcars$cyl*10
    })
    observe(
      updateSelectInput(
        session = session,
        inputId = "variable",
        choices = colnames(RV$data),
        selected = input$variable # only necessary if you want to keep the selection
      )
    )

    output$data <- renderDataTable({
      browser()
      DT::datatable(RV$data)
    })
  }
)

希望这有帮助!