Как отобразить выводимый текст внутри поля ввода текста в Shiny? - PullRequest
0 голосов
/ 02 сентября 2018

Я создаю блестящее приложение, в котором пользователи могут щелкнуть одну из ячеек таблицы 'renderDT', чтобы выбрать текст, а затем этот выбранный текст будет добавлен в поле ввода текста - функция, аналогичная введите текст на вашем телефоне, затем телефон предложит вам несколько слов-кандидатов. Затем вы можете нажать на одно из слов, слово автоматически перейдет в текстовое поле, чтобы закончить набор текста.

Мне удалось найти пример того, как получить значение ячейки, по которой щелкнули мышью, на выходе из здесь . Примерно так на 'server.R'

shinyServer(function(input, output,session) {
  output$inputecho <- reactive({
    input$inputtext
  })

  candidates <- reactive({

    candidates <- data.table(
                 candidate=c("word1","word2","word3") 
                 score=c(0.2,0.13,0.12) 
                  ) ### here candidates is a dummy data with same ###structure of real data.

    candidates<-as.data.frame(candidates)
    candidates

  })

output$candidates<-renderDT({candidates()},server=FALSE, selection = list(mode='single',target="cell"))

observeEvent(input$candidates_cell_clicked,{
  info=input$candidates_cell_clicked
  if (is.null(info$value)||info$col!=0)return()
  updateTextInput(session,'inputtext',value=paste0(inputtext,info$value))
})

 }
)

И это для 'ui.R'

shinyUI(fluidPage(

    mainPanel(

      textInput("inputtext", label="", value=" "),
      p("Click to select from the top candidate words:"),
      DT::dataTableOutput("candidates")
      )
  ))

Когда я запускаю приложение, кажется, что ячейка может отображаться как выбранная. Тем не менее, входной текст внутри моего ввода не обновляется. screenshot of the app with cell selected

1 Ответ

0 голосов
/ 02 сентября 2018

Попробуй это. Условие if было неправильно закодировано, и, следовательно, updateTextinput никогда не вызывался. Кроме того, inputtext нужно было назвать как input$inputtext, если вы хотите paste0 при щелчке по значению ячейки. Я оставлял комментарии в тех местах, где я вносил изменения. Кроме того, я использовал data.frame, а не data.table, не то чтобы это имело значение.

library(shiny)
library(DT)
library(shiny)

ui <- fluidPage(
  mainPanel(
    textInput("inputtext", label="", value=" "),
    p("Click to select from the top candidate words:"),
    DT::dataTableOutput("candidates")
  )
)

server <- function(input, output, session) {
  output$inputecho <- reactive({
    input$inputtext
  })

  candidates <- reactive({

    candidates <- data.frame( # changed from data.table
      candidate=c("word1","word2","word3") , # comma was missing
      score=c(0.2,0.13,0.12) 
    ) ### here candidates is a dummy data with same ###structure of real data.

    candidates<-as.data.frame(candidates)
    candidates

  })

  output$candidates<-renderDT({candidates()},server=FALSE, selection = list(mode='single',target="cell"))

  observeEvent(input$candidates_cell_clicked,{
    info=input$candidates_cell_clicked
    print(info$value)
    if (!(is.null(info$value)||info$col==0))# this was wrongly coded in your example
    {
    updateTextInput(session,'inputtext',value=paste0(input$inputtext,info$value)) # assuming you want to concatenate the two
    # if you want to just update the cell do value=info$value
      }

  })

}


shinyApp(ui, server)
...