Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display input text inside some other text in shiny?

I have an input box and whenever a user types his name, then the output should be like "hai mr.X, how are you?" where X is the input. This should only appear after first input and name should change from X to whatever based on input after onwards.

My ui.R and server.R codes are below:

ui.R

library(shiny)
shinyUI(fluidPage(
titlePanel("Employee Assesment"),
sidebarLayout(
sidebarPanel(
  textInput("name","Enter your name","")),
  mainPanel(("About this"),
  textOutput("name")
  )
  )
))

server.R

library(shiny)

shinyServer(function(input, output) {

output$name <- renderText({input$name})

})
like image 755
Victor Johnzon Avatar asked Aug 18 '17 16:08

Victor Johnzon


1 Answers

I think there are a couple things that need to be addressed in this question. First of all, the place you would put the server logic, such that it drives a specific output, is in the server function. In the renderText function, you can put any type of interactive expression. In your case, this might be

  output$name <- renderText({
      if(input$name != ""){
        paste0("Oh hai Mr. ", input$name, ". How are you?"
      }
    })

At the same time, this doesn't have any control flow other than not displaying while a name is blank. Instead, you might want to consider adding a submitButton or actionButton in order to allow people to submit their name once they are finished typing this.

Here is how you would include that:

sidebarPanel(
      textInput("name","Enter your name",""),
      actionButton(inputId = "submit",label = "Submit")
)

To access the actionButton's control flow, you can set up a reactive expression triggered by the event. For example, we are going to call it "name."

  name <- eventReactive(input$submit, {
    if(input$name != ""){
      paste0("Oh hai Mr. ", input$name, ". How are you?")
    } else {
      "Please write a name."
    }
  })

Then when we want to refer to it, we can use it in our call to output$name like so:

 output$name <- renderText({
    name()
  })

This way, people's names will only appear once they have actually written a name, and otherwise they get an error message prompting them to write something.

like image 191
be_green Avatar answered Nov 14 '22 23:11

be_green