如何在R Shiny应用程序中实现和显示带有可点击单词的句子



我设计了一个闪亮的应用程序,它的特点之一是从基本语料库中生成新的句子(通过Markov字符串(。假设我生成了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模型(cfplotly软件包(上可以点击,以便将点击的单词用作其他操作的输入。

理想情况下,以一种附加但次要的方式,我甚至希望这些单词可以由用户手动替换。

到目前为止,我已经研究了不同的闪亮组件(闪亮底座、htmlwidgets、plotly等(,但没有找到令人满意的解决方案,我依赖于您的想法和建议,

非常感谢

这是一种实现应用程序的可能方法,只需使用显示多个句子的基本Shiny函数,点击每个单词即可创建一个仅包含该单词的新输入,然后可以用于其他计算或过程。

我所做的是手动创建一个围绕每个单词的HTML超链接标签,并使用Shiny.setInputValueJavascript函数创建一个新的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)

一个选项是将语句作为数据表处理

library(shiny)
library(DT)
library(plyr)
ui <- fluidPage(
# Original sentences as a table
DT::dataTableOutput('tableId'),
# Show the selected word(s) separately 
textOutput("text")
)
server <- function(input, output) {
sentences <-  reactive({
orig_sentences <- c(rep(c("This is a test sentence of moderate length", "This is another with different length"),5))
# Split sentences on whitespace, make a table with plyr 
t <- ldply(t(strsplit(orig_sentences, " ")), rbind)
})
output$tableId <- DT::renderDataTable(
sentences(), selection = list(target = 'cell')
)

output$text <- renderText({
# Get the selected cell(s) and get the cell value accordingly
cell <- input$tableId_cells_selected
sentence <- sentences()[cell]
})
}
shinyApp(ui = ui, server = server)

这张桌子不是最漂亮的解决方案。更便于读者阅读,但不是那种编程优雅的方式是在每个单元格上都有完整的句子。从句子表中选择一个单元格可以用所选句子中的单词作为单元格来填充新的数据表。

关于问题的第二点:如果你想替换单词,你可以将句子存储为reactiveValues,并制作自己的替换函数,将textInput中的值存储到选定的单元格中。

最新更新