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

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

我正在尝试制作一个使用此功能的 Shiny 应用程序(在 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)

我用这个函数得到了想要的结果:

现在这是我将其集成到闪亮的应用程序中的尝试:

UI 部分:

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

这里是服务器部分:

#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")
    })

尝试 运行 应用程序时,出现错误:

错误:arg必须是符号

我是不是在UI区或者服务器区做错了什么?如何在 Shiny 中正确使用 varSelectInput 制作交互式 ggplot,其中可以更改变量以更改绘图?

非常感谢!

markdown 代码与 Shiny 代码之间的主要区别是 Shiny 传递变量的字符串值 ("economic_freedom"),而 markdown 中的函数已编写为使用裸列名称 (economic_freedom).

更改函数以处理可以使用 .data 而不是 {{}} 的字符串。

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")
})

将“bang bang”运算符与 dplyr::sym() 一起使用也应该有效。

#Factor Comparisons
output$ls_vs <- renderPlot({
  dataset%>%
    filter(!!sym(input$variable) != 254.948530) %>% 
    filter(!!sym(input$variable) != 121.738080) %>%
    ggplot(mapping = aes(y = life_satisfaction, x = !!sym(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")
})