无论如何在 Shiny 应用程序中输入 zoo::rollmean() 中的字符串?

Is there anyway to take a string input in zoo::rollmean() in a Shiny app?

我是第一次创建 Shiny App,我 运行 遇到了 reactiv 的输入和输出问题。

我正在从用户那里获取状态、数据类型和滚动平均值的输入,以创建冠状病毒数据图。

要使 zoo::rollmean() 正常工作,我需要一个直列对象名称,例如 rollmean(deaths, k=3, fill=NA).

如何获取字符串输入并将其放入 rollmean() 函数?我已经搜索了一段时间的答案,但找不到任何东西。谢谢!

此代码无效:

ui:

selectInput(inputId = "data_point", 
  selected = "deaths", 
  label = "Type of Data,
  choices = c("Deaths" = "deaths",
              "Tests" = "people_tested",
              "Confirmed Cases" = "confirmed",
              "Recovered" = "recovered"))

服务器:

  output$covid_plot <- renderPlot({
    statedata %>%
      arrange(desc(state)) %>% 
      group_by(state) %>% 
      mutate(three_day = rollmean(input$data_point, k = 3, fill = NA),
             five_day = rollmean(input$data_point, k = 5, fill = NA),
             seven_day = rollmean(input$data_point, k = 7, fill = NA),
             fifteen_day = rollmean(input$data_point, k = 15, fill = NA))

此代码将:

ui:

selectInput(inputId = "data_point", 
  selected = "deaths", 
  label = "Type of Data,
  choices = c("Deaths" = "deaths",
              "Tests" = "people_tested",
              "Confirmed Cases" = "confirmed",
              "Recovered" = "recovered"))

服务器:

output$covid_plot <- renderPlot({
 statedata %>%
 arrange(desc(state)) %>% 
 group_by(state) %>% 
 mutate(three_day = rollmean(deaths, k = 3, fill = NA),
      five_day = rollmean(deaths, k = 5, fill = NA),
      seven_day = rollmean(deaths, k = 7, fill = NA),
      fifteen_day = rollmean(deaths, k = 15, fill = NA))

伪造类似 shiny 的环境:

input <- list(var = "disp")

基础 R

head(mtcars) %>%
  mutate(z = zoo::rollmean(get(input$var), k = 3, fill = NA))
#    mpg cyl disp  hp drat    wt  qsec vs am gear carb        z
# 1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4       NA
# 2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 142.6667
# 3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 175.3333
# 4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 242.0000
# 5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 281.0000
# 6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1       NA

tidyeval

inp <- sym(input$var)
head(mtcars) %>%
  mutate(z = zoo::rollmean(!!inp, k = 3, fill = NA))
#    mpg cyl disp  hp drat    wt  qsec vs am gear carb        z
# 1 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4       NA
# 2 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4 142.6667
# 3 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1 175.3333
# 4 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1 242.0000
# 5 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2 281.0000
# 6 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1       NA

或者只是

head(mtcars) %>%
  mutate(z = zoo::rollmean(!!sym(input$var), k = 3, fill = NA))