Search code examples
rshinydata.tableselectinput

Shiny: assign var names dynamically based on selectInput selection


I am triyng to use a selectInput to subset a data.table to the selected column, preserving its name. So far I have done:

library(data.table)
mtcars <- data.table(mtcars)

ui <- bootstrapPage(
  uiOutput('variables'),
  tableOutput('table')
)

server <- function(input, output) {
  output$variables<- renderUI ({
    selectInput('var', 
                label = 'select Vars:', 
                choices = as.list(colnames(mtcars)),
                multiple = F)
  })


  df <- reactive({
    df <- mtcars[, list(var_name=get(input$var)), ]
  })

  output$table <- renderTable({head(df())})

}

shinyApp(ui = ui, server = server)

and the output is

enter image description here

But what I really wants is that the column name is the same as in the original df. I have tried options with no success, like:

    df <- mtcars[, list(input$var), ]
    df <- mtcars[, list(paste0(input$var)=get(input$var)), ]

but neither gave me the desired output... Any ideas ? thanks in advance


Solution

  • Do you mean something like this? :

    df <- reactive({
        df <- mtcars[, list(var_name=get(input$var)), ]
        colnames(df) <- input$var
        df
    })
    

    Obviously you can then edit the colname to something else as well