Shiny dplyr and sparkline example

477 views Asked by At

I'm having a hard time getting these sparklines to work with Shiny. The following code gives the desired output:

library(dplyr)
library(sparkline)

dfSpark <- data.frame(month = rep(1:12, len = 38),
                  year = floor(2010 + (1:38)/12),
                  value = runif(38, 0, 5))

dfSpark %>%
  group_by(month, month.abb[month]) %>%
  summarise(
    value = spk_chr(
      value, type = "line",
      chartRangeMin = 0, chartRangeMax = max(dfSpark$value)
    )
   ) %>%
  arrange(month) %>%
  ungroup() %>%
  select(-month) %>%
  setNames(., c("Month", "Trend")) %>%
  formattable() %>%
  formattable::as.htmlwidget() %>%
  spk_add_deps()

However, when I try to put it in a Shiny Application, it returns "Error: object of type 'closure' is not subsettable."

Here is the code for the Shiny App:

library(shiny)
library(dplyr)
library(sparkline)

ui <- fluidPage(
  titlePanel("Sparkline Example"),
  sidebarLayout(
      sidebarPanel(
         sliderInput("mths",
                     "Number of months:",
                     min = 24,
                     max = 72,
                     value = (72+24)/2)
      ),

      mainPanel(
         sparklineOutput("sparkPlot", height = "300px")
      )
   )
)

server <- function(input, output) {

   sparkData <- reactive({
     mths <- input$mths
     dfSpark <- data.frame(month = rep(1:12, len = mths),
                           year = floor(2010 + (1:mths)/12),
                           value = runif(mths, 0, 5)
     )
     return(dfSpark)
   })
   output$sparkPlot <- renderSparkline({
     sparkData() %>%
       group_by(month, month.abb[month]) %>%
       summarise(
         value = spk_chr(
           value, type = "line",
           chartRangeMin = 0, chartRangeMax = max(sparkData$value)
         )
       ) %>%
       arrange(month) %>%
       ungroup() %>%
       select(-month) %>%
       setNames(., c("Month", "Trend")) %>%
       formattable() %>%
       formattable::as.htmlwidget() %>%
       spk_add_deps()
  })
}
shinyApp(ui = ui, server = server)

I've tested the output of sparkPlot by putting in a dummy sparkline and it works, too.

Thanks in advance for your help!

0

There are 0 answers