首页 > 解决方案 > 如何在 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 等)但没有找到令人满意的解决方案,我依赖于你的想法和建议,

非常感谢

标签: rshinyplotlyr-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)

推荐阅读