r - 如何在 R Shiny 应用程序中实现和显示带有可点击单词的句子?
问题描述
我设计了一个闪亮的应用程序,它的一个特点是从基础语料库中生成新句子(通过马尔可夫字符串)。假设我生成了 10 个长度适中的句子。
sentences <— c(rep(c("This is a test sentence of moderate length", "This is another test sentence of moderate length"),5))
我希望能够在我的 Shiny 应用程序中非常清楚地显示这些句子,每行一个,允许一点交互性。特别是,我希望这些词可以在plotly_click模型(cf plotly包)上单击,以便将单击的词用作其他操作的输入。
理想情况下,以一种额外但次要的方式,我什至希望用户可以手动替换这些单词。
到目前为止,我已经研究了不同的闪亮组件(闪亮的基础、htmlwidgets、plotly 等)但没有找到令人满意的解决方案,我依赖于你的想法和建议,
非常感谢
解决方案
这是实现应用程序的一种可能方式,仅使用显示多个句子的基本 Shiny 函数,单击每个单独的单词会创建一个仅包含该单词的新输入,然后可以将其用于其他计算或过程。
我所做的是手动创建一个包裹在每个单词周围的 HTML 超链接标签,并使用Shiny.setInputValue
Javascript 函数创建一个新的 Shiny 输入,input$word
只要用户点击给定的单词,就可以调用该输入。为了证明已经创建了一个可以在其他地方使用的新输入,我刚刚将它打印在主列表下方,renderText
您会看到,每当您点击不同的单词时,都会textOutput
更新以打印点击的单词:
library(shiny)
ui <- fluidPage(
uiOutput("sentences"),
br(),br(),
textOutput("word")
)
server <- function(input, output) {
sentences <- c(rep(c("This is a test sentence of moderate length", "This is another test sentence of moderate length"),5))
output$sentences <- renderUI({
link_sentences <- lapply(sentences, function(x) {
words <- unlist(strsplit(x, " ", fixed = TRUE))
sentence <- paste0("<a href='#' onclick='Shiny.setInputValue(\"word\", \"", words, "\");'>",
words,
"</a>",
collapse = "",
sep = " ")
HTML(paste("<br>", sentence, "</br>"))
})
do.call(tagList, link_sentences)
})
output$word <- renderText(input$word)
}
shinyApp(ui = ui, server = server)
推荐阅读
- python - tkinter,python 3.7中的.get()问题
- javascript - 是否可以仅使用 nodejs 阻止表单提交?
- python - keras CosineSimilarity 度量和目标向量和预测向量之间计算的余弦相似度之间的差异
- c++ - 如何在二进制文件中保存和读取链接列表?
- macos - 如何根据文件 Mac 的前三个字符将项目移动到文件夹
- sql - 如何使用 SQL 选择所有非数字的值?
- node.js - 网站的基本身份验证,以保护网站登录和 API 访问
- python - 有没有比 count() 更快的方法来计算字符串中的非重叠出现?
- javascript - 功能仅在单击两次时有效
- powerbi - 将逗号分隔的文本转换为数字列表