COLO
COLO

Reputation: 1114

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

Upvotes: 1

Views: 52

Answers (2)

Qwfqwf
Qwfqwf

Reputation: 518

You could re-assign the column name after you subset:

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

Upvotes: 0

KGee
KGee

Reputation: 815

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

Upvotes: 0

Related Questions