[英]In shiny, selecting unique values from a column in a reactive object to use as input choices
我正在尝试制作 shiny 仪表板应用程序,其中下拉菜单中可用的选项是从反应数据 object 的列中检索的。
目前我的代码看起来像这样:
library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(tidyverse)
data <- reactiveFileReader(
intervalMillis = 100000,
NULL,
filePath = 'Data\\data.csv',
readFunc = read.csv,
fileEncoding="UTF-8-BOM"
)
header <- dashboardHeader(title = "test")
sidebar <- dashboardSidebar(
sidebarMenu(
menuItem("plots", tabName = "plots"),
pickerInput('to','To:',
options = list(`actions-box` = TRUE, size = 10), multiple = TRUE,
choices = NULL)
)
)
fluid1 <- fluidRow(
box()
)
body <- dashboardBody(
tabItems(
tabItem(
tabName = 'plots', h2(fluid1)
)
)
)
ui <- dashboardPage(title = 'test', header, sidebar, body, skin='blue')
server <- function(input, output){
choices <- reactive({
data() %>%
select(to) %>%
unique()
})
observe({updatePickerInput('to',choices = choices())})
}
shinyApp(ui = ui, server = server)
以及一些示例数据:
data <- data.frame(from = c('RCD', 'RCD', 'RCR', 'RCD', 'RCS', 'RCR', 'RCR', 'RCS', 'RCO', 'RCS'),
to = c('RCS', 'RCR', 'RCO', 'RCO', 'RCR', 'RCD', 'RCS', 'RCD', 'RCR', 'RCO'),
n = c(1,2,3,4,5,6,7,8,9,10))
我所期望的是这个 -
choices <- reactive({
data() %>%
select(to) %>%
unique()
})
给我data()
反应 object 的to
列中的唯一值列表,然后我可以将其传递给observe({updatePickerInput('to',choices = choices())})
相反,我收到此错误:
Warning: Error in : $ operator is invalid for atomic vectors
我对使用 shiny 很陌生,所以在解决这个问题时遇到了真正的问题。 任何帮助将不胜感激
这经常出现。 您可能有一个有效的shiny
应用程序,其server
方法缺少session
参数。 但是,一旦您使用诸如updatePickerInput
、 updateSelectInput
、 updateTextInput
等方法,您就会遇到错误,因为它需要您将session
传递给它。 因此,您需要确保将session
参数包含到您的server
function 中:
server <- function(session, input, output) {
...
}
session
object 在许多情况下都有帮助,例如在浏览器关闭时执行某些操作、自定义用户界面、更新输入或向 javascript 发送消息。 有关更多信息,请参阅此实用答案。
对于updatePickerInput
,您实际上是在向会话客户端 web 页面上的选择器输入发送消息。 如果输入存在,则调用绑定对象的receiveMessage
方法。 updatePickerInput
是一个友好的包装器,可以代替通用的sendInputMessage
使用。 在这种情况下,尝试包括session
:
updatePickerInput(session, 'to', choices = choices())
session
object 的有用参考:
https://shiny.rstudio.com/reference/shiny/latest/session.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.