【问题标题】:How to use the result of using reactive function as input in ui? - r shiny如何在ui中使用使用反应函数作为输入的结果? -r 闪亮
【发布时间】:2021-04-19 01:49:19
【问题描述】:

我在服务器上使用了一个响应式函数来创建一个数据框。

并且我想在 UI 中将这个数据框的一列的唯一向量表示为 selectinput。

例如)

DATA<-data.frame(ID, NAME)

####server#####
DATAFRAME<-reactive({DATA[DATA$ID %in% input$ID,})

####UI######
selectizeInput("name",label="name:",choices=unique(DATAFRAME$NAME))

换句话说,我想显示一个名称列表,用于预先按 ID 提炼一次的数据。

【问题讨论】:

  • 使用reactive()时,您需要像这样添加()DATAFRAME()$NAME
  • 当我这样做时,我收到以下错误:`ERROR: could not find function "DATAFRAME"' @HubertL
  • 不能直接放到UI中。您需要调用 updateSelectInput 之类的函数来使用新值更新 UI。有关基本思想,请参阅此现有问题:stackoverflow.com/questions/46346917/…

标签: r user-interface server shiny reusability


【解决方案1】:

为了对响应式表达式DATAFRAME 的变化做出反应,您可以使用observer 并使用updateSelectizeInput 更新名称列表(正如@MrFlick 所指出的那样)。

library(shiny)

ui <- fluidPage(
    titlePanel("Widget Dependencies Sample App"),
    selectizeInput("IdSelect", "Choose ID", "N/A"), # IDs to select from
    selectizeInput("IdName", "Choose Name", "N/A"), # Names depend on selected ID
    tableOutput("IdDatatable") # show the whole data set to understand what happens
)

server <- function(input, output, session) {
  ID   <- paste("ID", 1:3, sep = "_")
  NAME <- LETTERS[1:(3*5)]
  DATA <- data.frame(ID, NAME)
  updateSelectizeInput(session, "IdSelect", choices = unique(ID))

  DATAFRAME <- reactive({DATA[DATA$ID %in% input$IdSelect, ]})

  observe({
   updateSelectizeInput(session, "IdName", choices = unique(DATAFRAME()$NAME))
  })

  output$IdDatatable <- renderTable(DATA)
}

shinyApp(ui = ui, server = server)

但是,如果您只需要一次反应式表达式DATAFRAME,您可以使代码更简单。在这种情况下,您不会观察到对小部件中的更改做出反应的 DATAFRAME。您可以省略 DATAFRAME 并直接观察输入小部件。该观察者生成Names 的过滤向量,并仅使用一个观察者更改selectizeInput 中的选择。

observe({
    Names <- DATA$NAME[DATA$ID %in% input$IdSelect]
    updateSelectizeInput(session, "IdName", choices = unique(Names))
})

【讨论】:

    猜你喜欢
    • 2020-10-28
    • 2020-08-18
    • 2020-07-04
    • 2020-08-01
    • 2021-05-25
    • 1970-01-01
    • 2017-07-17
    • 1970-01-01
    相关资源
    最近更新 更多