r - 如何在 Shiny App 中创建关键字搜索?
问题描述
我正在尝试构建一个闪亮的应用程序,以便用户可以与我在数据框中的一组句子“交互”。数据框如下所示:
# id: each sentence has a unique number
# file: name of the file the sentence comes from
# sentence: the actual sentence
# group: group the writer belongs to
# gender: writer's gender
id file sentence group gender
1 101s the tree is tall. A female
2 101s the sun is yellow. A female
3 102s he reads a book. D male
4 102s she goes shopping. D male
5 103s they drive the car. B female
...
我想使用 R Shiny 创建一个“上下文中的关键字”搜索栏。基本上,用户输入一个单词,应用程序就会检索包含该单词的句子。
这是我包含在我的ui.R
文件中用于特定目的的代码:
sidebarPanel(
textInput("Input_KWIC", "Enter a keyword:"),
mainPanel(htmlOutput("Text_KWIC")))),
这是我包含在我的server.R
文件中的代码。
output$Text_KWIC = renderUI({
data %>%
filter(grepl(input$Input_KWIC, sentence)) %>%
pull(sentence)
})
当我运行应用程序时,我收到此错误:“要写入的文本必须是长度为 1 的字符向量”(这是在我输入关键字之后)。
我不知道我做错了什么,也不知道错误是在 UI 中还是在服务器中。
解决方案
您收到错误消息,因为您设置服务器功能的方式可能会导致一种以上的结果。请记住,当应用程序启动时,文本框是空的,因此您的函数的返回是一个具有多个值(实际上是所有值)的向量,并且 renderUI 只消化“闪亮的标签对象、HTML 或列表这样的对象”。
现在您可以搜索值并再次获得响应,但有时响应向量具有多个值/项,这将导致相同的错误。
所以这是你可以做的:
只需选择搜索结果的第一个值:
data %>% dplyr::filter(grepl(input$Input_KWIC, sentence)) %>% dplyr::pull(sentence) %>% .[1]
将输出转换为列表
df %>% dplyr::filter(stringr::str_detect(sentence, pattern = input$Input_KWIC)) %>% dplyr::pull(sentence) %>% as.list()
将renderUI() 和htmlOutput() 更改为renderText() 和textOuput(),这将使您获得一个接一个列出的所有结果字符串
可能会起作用,但需要更多努力:在渲染函数中为多个值构建 html 输出
遵循@rawrs 的建议并使用某种表格输出