如何将Shiny的SelectInput传入startswith函数?解决无数据返回问题
问题分析与解决方案
你的代码存在三个核心问题,导致无数据返回:
1. startsWith参数顺序颠倒
startsWith的正确语法是startsWith(x, prefix),其中x是要检查的字符向量,prefix是前缀文本。你现在把列名(input$select1/input$select2)传给了第一个参数,实际应该传入所选列的具体数据。
2. data.table行筛选逻辑错误
当前代码是用「列名是否匹配搜索文本」的结果来筛选行,而不是用「所选列的内容是否匹配搜索文本」。需要先提取所选列的数值/字符向量,再进行匹配。
3. 按钮触发条件判断错误
sidebarSearchForm生成的按钮对应的input$searchButton是点击次数(数值型),每次点击会递增1,不是布尔值。input$searchButton == TRUE永远无法满足,导致req条件一直不通过,后续代码不会执行。
修正后的完整代码
library(shiny) library(shinydashboard) library(DT) library(data.table) Name <- c("Martin Lawrence", "Will Smith", "Harrison Ford", "Tom Hanks") Age <- c(55, 50, 85, 60) Table1 <- data.table(Name, Age, stringsAsFactors = FALSE) Name <- c("Jim Carrey", "Mark Wahlberg", "Harrison Ford", "Tom Hanks") Age <- c(55, 45, 85, 60) Table2 <- data.table(Name, Age, stringsAsFactors = FALSE) ui <- dashboardPage( dashboardHeader(title = "Searching Dashboard"), dashboardSidebar( width = 300, sidebarMenu( sidebarSearchForm( textId = "searchText", buttonId = "searchButton", label = "Search Dataset" ), tags$br(), menuItem( "Show Data", tabName = "tabset3", icon = icon("info", lib = "font-awesome") ), selectInput("select1", "Select columns to search from Table1", names(Table1), multiple = FALSE), tags$br(), selectInput("select2", "Select columns to search from Table2", names(Table2), multiple = FALSE) ) ), dashboardBody(scrollx = TRUE, tabItems( tabItem(tabName = "tabset3", fluidRow( tabBox( title = "Matching Data", id = "tabset3", height = "550px", width = "500px", tabPanel("Table 1", div(style = 'overflow-x: scroll;', DTOutput('table1'))), tabPanel("Table 2", div(style = 'overflow-x: scroll;', DTOutput('table2'))) ) )) ) ) ) server <- function(input, output, session) { output$table1 <- renderDT({ # 检查按钮是否被点击过,且搜索文本不为空 req(input$searchButton > 0, input$searchText) # 提取所选列的向量,用startsWith匹配前缀 match_vec <- startsWith(Table1[[input$select1]], input$searchText) # 筛选匹配的行 Table1[match_vec] }) output$table2 <- renderDT({ req(input$searchButton > 0, input$searchText) match_vec <- startsWith(Table2[[input$select2]], input$searchText) Table2[match_vec] }) } shinyApp(ui , server)
关键修改说明
- 调整
startsWith参数:用Table1[[input$select1]]提取所选列的实际数据,作为第一个参数传入startsWith,第二个参数是搜索文本input$searchText。 - 修正按钮触发条件:用
input$searchButton > 0判断按钮是否被点击过,同时增加input$searchText的检查,避免空搜索。 - 优化data.table筛选:先生成匹配逻辑向量
match_vec,再用该向量筛选行,逻辑更清晰。
内容的提问来源于stack exchange,提问作者Ahmed
相关产品推荐
相关产品推荐

