You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R Shiny中实现从dataframe查询并返回正确结果的搜索功能

问题修正方案

核心问题梳理

  • 过滤逻辑硬编码为固定值"a",未关联搜索输入框的用户输入,应该使用input$a读取输入内容
  • UI部分存在冗余错误代码(outputId = "tablom"),,属于无效语法,直接保留tableOutput组件即可
  • 原始数据框定义存在语法错误,多写了data_frame = 标识,且长字符串换行不规范
  • 默认用==全等匹配要求输入内容和基因名完全一致,若需要模糊搜索需要更换匹配逻辑

注意:代码中用到的searchInput组件来自shinyWidgets扩展包,运行前需执行install.packages("shinyWidgets")完成安装

修正后完整可运行代码(精准匹配版本)

输入完整基因名才会返回对应结果:

library(shiny)
library(shinyWidgets)
library(dplyr)

# 修正后的数据框定义
table1 <- data.frame(
  Ciliopathy = c("Acrocallosal Syndrome" ,"Alström Syndrome" , "Ataxia-telangiectasia-like Disorder" ,"Ataxia-telangiectasia-like Disorder" , "Autosomal Dominant Polycystic Kidney Disease (ADPK)" ,"Autosomal Dominant Polycystic Kidney Disease (ADPK)" , "Autosomal Dominant Polycystic Kidney Disease (ADPK)", "Autosomal Dominant Polycystic Kidney Disease (ADPK)","Autosomal Dominant Polycystic Kidney Disease (ADPK)"),
  OMIM.Phenotype.Number = c(200990,203800,604391,615919,173900,613095,613095,600666,600666),
  Human.Gene.Name = c("KIF7","ALMS1","MRE11","PCNA","PKD1","PKD2","PKD2","GANAB","GANAB")
)

ui <- fluidPage(
  tags$h1("Search Input"),
  br(),
  searchInput(
    inputId = "a", label = "Enter your text",
    placeholder = "A placeholder",
    btnSearch = icon("search"),
    btnReset = icon("remove"),
    width = "450px"
  ),
  br(),
  tableOutput("tablom")
)

server <- function(input, output, session) {
  generow = reactive({
    # 读取用户输入,全等匹配基因名
    table1 %>% filter(Human.Gene.Name == input$a)
  })  
  output$tablom <- renderTable({ 
    generow()
  })
}

shinyApp(ui = ui, server = server)

可选优化:模糊搜索版本

如果需要输入部分字符就能搜到对应结果,比如输入PK就能返回PKD1、PKD2的结果,把reactive部分的代码替换为以下内容即可:

generow = reactive({
  # 忽略大小写的模糊匹配
  table1 %>% filter(grepl(input$a, Human.Gene.Name, ignore.case = TRUE))
})

内容的提问来源于stack exchange,提问作者ziya zorluer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 17:48:01