Summarize using dplyr and shiny

2019-08-25 23:20发布

问题:

I currently have an app setup where it lets the user input which variable they want to plot and visualize. I am running into an issue when I am trying to pass off the shiny input variable into summarize.

testData <- plotData %>% 
        summarize(means=mean(input$selectedMetric, na.rm=TRUE)) %>%
        summarize(sd=sd(input$selectedMetric, na.rm=TRUE))

The error I get is the following:

Warning in mean.default(input$selectedMetric, na.rm = TRUE) :
argument is not numeric or logical: returning NA

How am I supposed to set it up so that it takes the mean and standard deviation of whatever selected column the user decides?

回答1:

There a few things can go wrong here:

  • You are not checking for null when using input$selectedMetric

  • You improperly using reactives. You should access the reactives by using () at the end as they are functions that return something.

Below Im assuming that your plotData variable isn't a reactive and its a declared object

testData <- reactive({
  if(is.null(input$selectedMetric)){
    return()
  }
  plotData %>% 
    summarize(means=mean(input$selectedMetric, na.rm=TRUE)) %>%
    summarize(sd=sd(input$selectedMetric, na.rm=TRUE))
})

testData()

You can access the summary, like so: testData()



标签: r shiny dplyr