简体   繁体   English

R Shiny:根据从 selectInput 中选择的问题动态显示文本

[英]R Shiny: Dynamically display text based on chosen question from selectInput

I am building a Shiny app, and want the app to display an answer text from a Q&A list stored as a csv file based on what question the user choose in a drop down list.我正在构建一个 Shiny 应用程序,并希望该应用程序根据用户在下拉列表中选择的问题显示存储为 csv 文件的问答列表中的答案文本。 I am new to Shiny so would be really grateful for beginner explanation and example code.我是 Shiny 的新手,因此非常感谢初学者的解释和示例代码。

I have stored a list in a csv-file which contains a list of questions and answers.我在一个包含问题和答案列表的 csv 文件中存储了一个列表。

So, this is what I need the app to do:所以,这就是我需要该应用程序执行的操作:

First, the user will choose an option in a drop down list I have created with selectInput.首先,用户将在我使用 selectInput 创建的下拉列表中选择一个选项。

Second, I want the app to display a paragraph of text, based on the choice that the user has made.其次,我希望应用程序根据用户所做的选择显示一段文本。 The text to be displayed is stored in the csv file, which contains basically two columns: all the different choices/questions in columnA, and the corresponding answer in the second column, columnB.要显示的文本存储在 csv 文件中,该文件基本上包含两列:列 A 中的所有不同选择/问题,以及第二列列 B 中的相应答案。

So the app needs to find the correct answer to be displayed based on the question that the user chooses from the choices in the selectInput.因此,应用程序需要根据用户从 selectInput 中的选项中选择的问题找到要显示的正确答案。

How do you achieve this?你如何做到这一点?

Many thanks in advance!提前谢谢了!

You are able to do this with the code below.您可以使用以下代码执行此操作。 You'll need remove the hard-coded answers data I've put in and uncomment the line that reads the answers from csv .您需要删除我输入的硬编码answers数据,并取消注释从csv读取答案的行。 Similarly for the question choices.类似的问题选择。

library(shiny)

# answers <- read.csv('path/to/file')
question_choices <- c('question 1', 'question 2')
# question_choices <- answers$q

ui <- fluidPage(
  selectInput(
    'question',
    'Select Question:',
    choices = question_choices
  ),
  textOutput('answer')
)

server <- function(input, output, session) {
  answers <- tribble(
    ~q, ~a,
    'question 1', 'answer 1',
    'question 2', 'answer 2'
  )
  
  output$answer <- renderText({
    answers[answers$q == input$question, ]$a
  })
}

shinyApp(ui, server)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM