如何使 mutate 对数字列名称具有反应性?

How to make mutate work with reactive on numerical column names?

我真的不知道在处理数字列的名称时将 mutate 与 reactive 挂钩。

我有这样的数据:

df <- tibble(a=c("a", "b", "c"), `1990`=c(1,2,3), `2010`=c(3,2,1))

当我这样做时一切看起来都很好:

p <- df %>%
  mutate(newvar = `1990`)

但我想在我的 Shiny App 中使用它,以便将 newvar 分配给 select 列表中的输入。

我为此创建了这个反应式;

  selectedyear <- reactive({
    input$select
  })

但是现在好像不行了:

p <- df %>%
  mutate(newvar = selectedyear())

我尝试了不同的修改,例如:

p <- df %>%
  mutate(newvar = `selectedyear()`)

但似乎没有什么适合我。

应用的完整代码:

library(shiny)
library(tibble)
library(dplyr)

df <- tibble(a=c("a", "b", "c"), `1990`=c(1,2,3), `2010`=c(3,2,1))

ui <- fluidPage(
  selectInput("select", "Select:", c(1990, 2010)),
  tableOutput("val")
)
server <- function(input, output) {
  selectedyear <- reactive({
    input$select
  })
  output$val <- renderTable({
    p <- df %>%
      mutate(temperature = selectedyear())
    p
  })
}
shinyApp(ui, server)

同样的事情,但是用字符作为输入很容易。你知道这方面的技巧吗?

你可以做到

  output$val <- renderTable({
    p <- df %>%
      mutate(temperature = !!selectedyear())
    p
  })

问题似乎是列 19902010 的非语法名称。下面的方法应该有效。它在 mutate 调用的右侧使用 eval/parse。请注意,您通常不需要创建 reactive 的(并且只有)输入,因为每个输入都已经是反应性的。

library(shiny)
library(tibble)
library(dplyr)

df <- tibble(a=c("a", "b", "c"), `1990`=c(1,2,3), `2010`=c(3,2,1))

ui <- fluidPage(
  selectInput("select", "Select:", c(1990, 2010)),
  tableOutput("val")
)
server <- function(input, output) {


  output$val <- renderTable({

       df %>%
          mutate(temperature = eval(parse(text = paste0("`", input$select,"`"))))

  })
}
shinyApp(ui, server)

如果您只对温度列感兴趣并且不需要显示其余数据,那么 dplyr::select 可以让您以更直接的方式访问 input$select 变量:

  output$val <- renderTable({

    df %>% 
      select(temperature = input$select)

  })