Shiny app fails with "argument 1 (type 'closure') cannot be handled by 'cat'" - what does this mean?

L Mico picture L Mico · Apr 9, 2016 · Viewed 11.3k times · Source

I am building a Shiny app that takes a user's text input, compares the last two words to a data frame of trigrams to predict the most likely next word. In server.R below the output of the triPred function which I am trying to ouptut is a single word. When I load this app I get the following error after I type some text into the app - 'argument 1 (type 'closure') cannot be handled by 'cat' - which appears to be related to the final line in server.R As this is just a single word, I am unclear what is failing with 'cat' ie concatenate.

server.R

library(stringr)

shinyServer(function(input, output) {

    triSplit <- function(input) {
            el <- unlist(str_split(input," "))
            bigram <- paste(el[length(el)-1],el[length(el)])
            return(bigram)
    }

    triPred <- function(input) {
            ## pulls out end words that match the input bigram
            temp_wf_T <- wf_T[wf_T$start == triSplit(input),]
            ##Picks one of the best options at random based on count
            ans <- sample(temp_wf_T$end[temp_wf_T$count == max(temp_wf_T$count)],1)
            return(ans) }

    ##Read in a dataframe of bigrams, their possible completions, and counts of occurence
    wf_T<-readRDS("C:/Users/LTM/DataScienceCertificateCapstone/ShinyTest/data/tdm.rds")
    ##Runs the triPred function to guess the next most likely word
    ans <- reactive(triPred(input$sent))
    ##generates an output variable to display
    output$out <- renderText({ans})
    })

ui.R

library(shiny)

shinyUI(fluidPage(
    titlePanel(h1("My Shiny App", align = "center")),
    sidebarLayout(
            sidebarPanel(helpText("Please enter a sentence you would like me to complete"),
            textInput("sent", label = "sentence")),
            ##########
            mainPanel(h1("Best Guess"),
            br(),
            textOutput("out")
            )
    )
))

Answer

Vincent Bonhomme picture Vincent Bonhomme · Apr 9, 2016

It's hard to tell since I can't reproduce your app, but you should try with:

output$out <- renderText({ans()}) or just output$out <- renderText(ans()).

If you omit the (), you access the reactive itself, and not the value of it. A bit like when you type foo instead of foo() for a function.