Hi,
You were pretty close:
- An error when you ended the
fluidPage. You ended after textInput instead of textOutput so it wasn't part of the UI
- The output had a wrong name.
selected_var instead of predicted_word
Here's the fix:
library(shiny)
ui <- fluidPage(headerPanel("What Will They Say Next?"),
textInput(inputId="predictor_words", label = "type in four words"),
textOutput(outputId="predicted_word")
)
server <- function(input, output){
output$predicted_word <- renderText({
paste("You have selected", input$predictor_words)
})
}
shinyApp (ui=ui, server=server)
The problem with this code is that the reactivity will run every time the input box predictor_words changes, meaning after every character you type in (try it
). This is most likely not what you want.... I've taken the liberty of creating a slightly different version of you app:
library(shiny)
ui <- fluidPage(headerPanel("What Will They Say Next?"),
textInput(inputId="predictor_words", label = "type in four words (comma separated)"),
actionButton("predictButton", "Predict"),
textOutput(outputId="predicted_word")
)
server <- function(input, output){
myWords = eventReactive(input$predictButton, {
unlist(strsplit(input$predictor_words, "\\s*,\\s*"))
})
output$predicted_word <- renderText({
paste("You have entered", length(myWords()), "words:", paste(myWords(), collapse = " "))
})
}
shinyApp (ui=ui, server=server)
- By adding an actionButton (called predictButton), we can wait with evaluating words until the user has finished typing.
- An
eventReactive is a piece of code that will create or update a variable when a condition is met (in this case the button clicked).
- Using string split (with some regex) we can split the string of words into individual words. "\s*,\s*" means we cut after every comma, ignoring any white space (\s*) before or after the comma.
- Finally, you can do whatever you like with the words, as the variable
myWords is now reactive and will trigger all code where it's seen, in this case print the output in renderText. Note that a reactive variable is a function and needs to be called with () after it's name (the rest is identical to a normal R variable)
Hope this helps,
PJ