Error when selecting variables (with `varSelectInput`) and using ggplot with Shiny (Error: `arg` must a symbol)

Advertisements

I am trying to make a Shiny app which uses this function (made in R markdown):

ls_vs <- function(variable) {
dataset %>%
  filter({{variable}} != 254.948530) %>% 
  filter({{variable}} != 121.738080) %>%
  ggplot(mapping = aes(y = life_satisfaction, x = {{variable}})) +
  geom_point(aes(color = region, shape = freedom_status), size = 2) +
  geom_smooth(color = "cyan") +
  labs(y = "Life Satisfaction", shape = "Freedom Status", color = "Continent")
}

ls_vs(economic_freedom)

I am getting the desired results with this function:

Now Here’s my attempt of integrating that into a shiny app:

The UI section:

tabPanel("Factor Comparision", 
               
               sidebarPanel(
                 varSelectInput(inputId = "variable", label = "Select Factor to Compare", data = dataset),
                 
                mainPanel(                                   
                  h1("Test"),           
                  plotOutput("ls_vs"),
                 )   
               )),
      

And here is the server section:

#Factor Comparisons
    output$ls_vs <- renderPlot({
      dataset%>%
        filter({{input$variable}} != 254.948530) %>% 
        filter({{input$variable}} != 121.738080) %>%
        ggplot(mapping = aes(y = life_satisfaction, x = {{input$variable}})) +
        geom_point(aes(color = region, shape = freedom_status), size = 2) +
        geom_smooth(color = "cyan") +
        labs(y = "Life Satisfaction", shape = "Freedom Status", color = "Continent")
    })

Upon trying to run the app, I’m getting the error:

Error: arg must a symbol

Have I done something incorrectly in the UI area or in the sever area? How does one correctly use varSelectInput in Shiny to make an interactive ggplot where one can change the variable to change the plot?

Thank you very much!

>Solution :

The main difference between the code in markdown vs that in Shiny is Shiny passes string value of the variable ("economic_freedom") whereas the function in markdown has been written to work with bare column names (economic_freedom).

Change the function to work with strings that can be done using .data instead of {{}}.

library(dplyr)
library(ggplot2)

output$ls_vs <- renderPlot({
  dataset%>%
    filter(.data[[input$variable]] != 254.948530) %>% 
    filter(.data[[input$variable]] != 121.738080) %>%
    ggplot(mapping = aes(y = life_satisfaction, x = .data[[input$variable]])) +
    geom_point(aes(color = region, shape = freedom_status), size = 2) +
    geom_smooth(color = "cyan") +
    labs(y = "Life Satisfaction", shape = "Freedom Status", color = "Continent")
})

Leave a ReplyCancel reply