如何使 summarize 对闪亮的用户输入做出动态反应?

How to make summarise react dynamically to shiny user's input?

我正在构建一个闪亮的应用程序,它需要在显示图表之前进行一些数据处理。
当我 'hard code' 来自 tidyr 包 summarise 函数中的参数时,我的应用程序运行良好。但是,当我使用 reactive() 功能使其动态时,它不起作用。

下面是我的例子,你知道怎么解决吗?

非常感谢您的帮助和最诚挚的问候!

有效

  selectedAAA <- reactive({
                 dplot <- mydata %>% 
                    filter(V1 %in% input$aaa, V2 %in% input$bbb) %>% 
                    group_by(date, V1, V2)
                 dplot <-  dplot %>% 
                   summarise(LT = mean(var, na.rm = TRUE))  %>% # here 'var' is the name of one variable in mydata dataset. Works if hardcoded
                   spread(Material_Type, LT)
                 rownames(dplot) <- dplot$date 
                dplot <- select(dplot, -c(V1, date))
                dplot[is.na(dplot)] <- 0
                dplot <- as.data.frame(dplot)
                })

这不行

   # reactive feature to make the graph interactive, based on user's input (selectInput whose id is 'LT')

   selectedLT <- reactive({
                  switch(input$LT,
                  "Label 1" = var1,
                  "Label 2" = var2)
                  })


  selectedAAA <- reactive({
                 dplot <- mydata %>% 
                    filter(V1 %in% input$aaa, V2 %in% input$bbb) %>% 
                    group_by(date, V1, V2)
                 dplot <-  dplot %>% 
                   summarise(LT = mean(selectedLT(), na.rm = TRUE))  %>% # here selectedLT() is the user's selected variable in mydata dataset. Does not work
                   spread(Material_Type, LT)
                 rownames(dplot) <- dplot$date 
                dplot <- select(dplot, -c(V1, date))
                dplot[is.na(dplot)] <- 0
                dplot <- as.data.frame(dplot)
                })

我收到以下错误消息:

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

首先,我相信summarise实际上来自dplyr。其次,我认为您可以尝试传递字符串而不是实际变量。改为使用 summarise_ 函数尝试以下操作。

  selectedLT <- reactive({
                  switch(input$LT,
                  "Label 1" = "var1",
                  "Label 2" = "var2")
                  })


  selectedAAA <- reactive({
                 dplot <- mydata %>% 
                    filter(V1 %in% input$aaa, V2 %in% input$bbb) %>% 
                    group_by(date, V1, V2)
                 dplot <-  dplot %>% 
                   summarise_(LT = mean(selectedLT(), na.rm = TRUE))  %>% # here selectedLT() is the user's selected variable in mydata dataset. Does not work
                   spread(Material_Type, LT)
                 rownames(dplot) <- dplot$date 
                dplot <- select(dplot, -c(V1, date))
                dplot[is.na(dplot)] <- 0
                dplot <- as.data.frame(dplot)
                })