0

I am having trouble with some code that I've written.

Here is a sample of the dataset: https://docs.google.com/spreadsheets/d/1C_P5xxzYr7HOkaZFfFiDhanqDSuSIrd2UkiC-6_G2q0/edit?usp=sharing

Objective: I have a dataset that contains a column of Purchase_Month, candy and freq of the number of times that type of candy was purchased in that given month.

I have an rPlot which I was to change based on the chosen Candy bar in the SelectInput. And output a line chart based on the number of times that candy was purchased that month.

I have my current code below, but it tells me that candyCount is not found.

        ## ui.R ##
        library(shinydashboard)
        library(rCharts)

        dashboardPage(
          dashboardHeader(title = "Dashboard"),

          dashboardSidebar(
            width = 150,
            sidebarMenu(
              menuItem("Dashboard", tabName = "dashboard", icon = icon("bar-chart"))
            )

          ),

          dashboardBody(

          sidebarPanel(

              htmlOutput("candy")

            ),
            mainPanel(
              showOutput("plot2", "polycharts")
            ))




            )

    ##server.R##   
        library(rCharts)
        library(ggplot2)
        library(ggvis)

    server <- function(input, output, session) { 

      output$candy <- renderUI({

        available2 <- dataset[(dataset$candy == input$candy), "candy"]

        selectInput(
          inputId = "candy",
          label = "Choose a candy:  ",
          choices = sort(as.character(unique(available2))),
          selected = unique(available2[1])
        )
      })
      observeEvent(input$candy, {
    candyChoice<- toString(input$customer_issue)
    print(candyChoice)
    candyCount<- dataset[dataset$candy == candyChoice, ]
  })
      })

      output$plot2 <- renderChart2({
        p2 <- rPlot(freq~purchase_month, data = candyCount, type = 'line')
        p2$guides(y = list(min = 0, title = ""))
        p2$guides(y = list(title = sprintf("%s Claims",input$candy)))
        p2$addParams(height = 300, dom = 'chart2')
        return(p2)
      })


      }

Updated Data: Why wouldn't this work?

  candyCount<- reactive({
    dataset[dataset$candy == input$candy, ]
    })

  output$plot2 <- renderChart2({
    p2 <- rPlot(freq~purchase, data = candyCount(), type = 'line')
    p2$guides(y = list(min = 0, title = ""))
    p2$guides(y = list(title = ""))
    p2$addParams(height = 300, dom = 'chart2')
    return(p2)
  })
Gary
  • 2,137
  • 3
  • 23
  • 41
  • Please provide a [minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). It's hard to help without some toy data. That said, you write in your preamble that you have a column named `Candy`, but in your code it says `"candy"` (shot in the dark). Remember, R is case sensitive. – Anders Ellern Bilgrau Oct 15 '15 at 17:25
  • I have provided a sample dataset. – Gary Oct 15 '15 at 17:29

2 Answers2

1

At available2 you're filtering the data about a selected candy with dataset$candy == input$candy. But you use the same available2 to determine which are the choices at selectInput. I'm guessing you wanted: available2 <- dataset[, "candy"].

user5029763
  • 1,903
  • 1
  • 15
  • 23
  • I'm just using `available2` to help create the subset in my `selectInput`. I think my main issue is at everything starting with the `observeEvent` function. When I print `CandyChoice`, the value changes whenever I change the `selectInput`. I just don't know how to get that value into `CandyCount` and then have it graph the data in `CandyCount`. – Gary Oct 15 '15 at 18:27
  • Regarding `available2`, notice you are trying to use an `input` that is supposed to be definied by the same `available2`. @amwill04 explained this better. Moreover, notice that you want to list all possible candies in `choices` and not just the one selected by the user. Maybe it would be clarifying to print `sort(as.character(unique(available2)))` out. – user5029763 Oct 15 '15 at 19:50
1
output$candy <- renderUI({

    available2 <- dataset[(dataset$candy == input$candy), "candy"]

    selectInput(
      inputId = "candy",
      label = "Choose a candy:  ",
      choices = sort(as.character(unique(available2))),
      selected = unique(available2[1])
    )
  })

In the above you are trying to subset by an input, which is inside your output. The selectInput needs to be inside UI.R.

A working basic example you may find useful.

library(shiny)
df <- read.csv("/path/to/my.csv")

ui <- shinyUI(pageWithSidebar(

       headerPanel('Candy Data'),
       sidebarPanel(
             selectInput('candy', 'Candy', unique(as.character(df[,2])), selected = "Twix")

         ),
       mainPanel(
             plotOutput('plot1')
         )
 ))

server <- shinyServer(function(input, output, session) {
  selectedData <- reactive({
    df[which(df[,2] == input$candy),3]
  })

  output$plot1 <- renderPlot({
    barplot(selectedData())
  })

})

shinyApp(ui, server)

In the above example the ui renders a selectInput which has the ID candy. The value, i.e the candy selected is now assigned to input$candy scope. In server we have a reactive function watching for any input change. When the user selects a new candy this function, df[which(df[,2] == input$candy),3] is saying "subset my data frame, df, by the new input$candy". This is now assigned to the selectedData(). Finally we render then boxplot.

EDIT

server.R

require(rCharts)
options(RCHART_WIDTH = 500)
df <- read.csv("path/to/my.csv")
shinyServer(function(input, output, session) {
  selectedData <- reactive({
    df[which(df[,2] == input$candy),]
  })

  output$plot1 <- renderChart({
    p <- rPlot(freq~purchase_month, data = selectedData(), type = "line")
    p$addParams(dom = 'plot1')
    return(p)
  })
})

ui.R

require(rCharts)
options(RCHART_LIB = 'polycharts')
shinyUI(pageWithSidebar(

  headerPanel('Candy Data'),
  sidebarPanel(
    selectInput('candy', 'Candy', unique(as.character(df[,2])), selected = "Twix")

  ),
  mainPanel(
    showOutput('plot1', 'polycharts')
  )
))

save files in directory and then runApp.

amwill04
  • 1,330
  • 1
  • 11
  • 18
  • Can you explain what is going on in this line: df[which(df[,2] == input$candy),3]? – Gary Oct 15 '15 at 18:31
  • Have expanded my answer a little. Also check out http://shiny.rstudio.com/tutorial/ – amwill04 Oct 15 '15 at 18:41
  • Thanks for the example, but I'm receiving the following error: Error in eval(i, data, env) : numeric 'envir' arg not of length one – Gary Oct 15 '15 at 18:58
  • Sorry @Nick, I had rearranged your csv and forgot to change the column it was subsetting on. Have fixed that, the example will work now – amwill04 Oct 15 '15 at 19:35
  • Does `selectedData` return `df` when it is called? – Gary Oct 15 '15 at 19:52
  • When I try to use this with `rCharts`, it tells me that Object `freq` is not found. – Gary Oct 15 '15 at 20:21
  • And why wouldn't my "Update" work that I posted in the original question? – Gary Oct 15 '15 at 20:44
  • Im unsure, im playing with it now. Can't say I have overly familiar with `rCharts` package. I get it running but for some reason the plot displays in my RStudio graphic display rather that the app window. Also bare in mind for ease I didnt split the above into a `ui.R` & `server.R` files. – amwill04 Oct 15 '15 at 21:30