Search code examples
rshinyflexdashboardsentimentr

Text highlighting using sentimentr and shiny on flexdashboard in r is throwing error "attempt to apply non-function"


I am designing an R FlexDashboard in which I am uploading CSV data using the following code:

# "File Upload" button
fileInput("file1", "Load CSV/TSV File:",
          accept = c("text/csv", "text/comma-separated-values, text/plain", 
          ".csv", "text/tab-separated-values", ".tsv") )
# whether 1st row is header?
checkboxInput("header", "Is first row the Header?", TRUE)

Then I am using reactive method for selecting dataset:

# reactive dataset
data_set <- reactive({
   req(input$file1)
   inFile <- input$file1
   data_set <- read.csv(inFile$datapath, header=input$header)
})

Here is the slider input for selecting a particular row from dataset column "Text":

# sidebar slider input
sliderInput("disp", "Select Text:", min = 1,  max = 100, value = 20)
actionButton("display","Highlight Sentiments")
hr()

HL1 <- eventReactive(input$display, { data_set()[input$disp, "Text"] })

Finally, using observe input, I am trying to highlight the selected text based on sentiment (negative or positive) using sentimentr package:

observeEvent(input$display3, {
    output$HLRes <- renderUI({ 

      require(dplyr)
      require(sentiment)

      HL1() %>% 
        as.character() %>%
        sentiment_by() %>% highlight()
    })
})

And when I want to display the highlighted text from above:

htmlOutput("HLRes")

I get the following error:

 Error: attempt to apply non-function

What am I doing wrong here?


Solution

  • I had the same issue today, and found this:

    https://github.com/trinker/sentimentr/issues/110

    As suggested, adding the following got it to work (sentiment_by object <- sb)

    attr(sb, "averaging.function") <- sentimentr::average_downweighted_zero

    Fixed it for me.