r - R闪亮中的多个反应选择输入
问题描述
我一直在使用以下代码来允许多个选择输入相互反应。因此,当一个被更改时,其他框中的值也会更新:
l <- NULL
l$name <- c('b','e','d','b','b','d','e')
l$age <- c(20,20,21,21,20,22,22)
l <- as.data.frame(l)
l$name <- as.character(l$name)
l$age <- as.numeric(l$age)
library(shiny)
server <- shinyServer(function(input,output, session){
data1 <- reactive({
if(input$Box1 == "All"){
l
}else{
l[which(l$name == input$Box1),]
}
})
data2 <- reactive({
if (input$Box2 == "All"){
l
}else{
l[which(l$age == input$Box2),]
}
})
observe({
if(input$Box1 != "All"){
updateSelectInput(session,"Box2","Choose an age", choices = c("All",unique(data1()$age)))
}
else if(input$Box2 != 'All'){
updateSelectInput(session,"Box1","Choose a name", choices = c('All',unique(data2()$name)))
}
else if (input$Box1 == "All" & input$Box2 == "All"){
updateSelectInput(session,"Box2","Choose an age", choices = c('All',unique(l$age)))
updateSelectInput(session,"Box1","Choose a name", choices = c('All',unique(l$name)))
}
})
data3 <- reactive({
if(input$Box2 == "All"){
data1()
}else if (input$Box1 == "All"){
data2()
}else if (input$Box2 == "All" & input$Box1 == "All"){
l
}
else{
l[which(l$age== input$Box2 & l$name == input$Box1),]
}
})
output$table1 <- renderTable({
data3()
})
})
ui <-shinyUI(fluidPage(
selectInput("Box1","Choose a name", choices = c("All",unique(l$name))),
selectInput("Box2","Choose an age", choices = c("All",unique(l$age))),
tableOutput("table1")
))
shinyApp(ui,server)
这适用于 2 个选择输入框,但我不知道如何添加更多。
我总共有 4 个选择输入需要相互反应(以及更新反应数据框)。
我是 R 和 Shiny 的新手。
解决方案
如果您只是想获取子集数据和/或过滤值,那么您的工作太辛苦了。该包使用过滤行的索引DT
填充输入值,并自动提供适合类的过滤器。请注意,我们subsetted_data()
在不同的渲染中使用 来生成更多的 ui 元素。
library("shiny")
library("DT")
ldata <- data.frame(
name = c('b','e','d','b','b','d','e'),
age = c(20,20,21,21,20,22,22)
)
#
server <- shinyServer(function(input,output, session){
output$ldata_table <- renderDataTable({
datatable(ldata, filter = "top")
})
subsetted_data <- reactive({
# the input$<shiny-id>_rows_all populated by the DT package,
# gets the indices of all the filtered rows
req(length(input$ldata_table_rows_all) > 0)
ldata[as.numeric(input$ldata_table_rows_all),]
})
output$state <- renderPrint({
summary(subsetted_data())
})
})
ui <- fluidPage(
dataTableOutput("ldata_table"),
verbatimTextOutput("state")
)
shinyApp(ui, server)
推荐阅读
- java - 来自 MongoDB BSON 的 Jackson ObjectMapper
- swift - 如何在 macOS 的自定义视图中正确添加 NSTextField 的 IBOutlet?
- html - 从元素/标签获取 ID
- php - 未调用 CI 的 API 响应获取方法
- powershell - 合并两个 CSV,然后在输出中重新排序列
- excel - Using Excel & Access Together passing a variable from excel to access
- sharepoint - 我们可以在一个应用程序中使用两个 SPFx 扩展吗
- javascript - 用于使用文本框提取特定图片的 javascript
- php - HTML 将宽度为 110% 的表格行居中
- android - 将视频分成几部分,在android中用base64编码每个部分