1

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

camille
  • 16,432
  • 18
  • 38
  • 60
COLO
  • 1,024
  • 16
  • 28

2 Answers2

0

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

KGee
  • 771
  • 7
  • 26
  • I formerly tried with colnames(df) <- input$var but since I did not add de df or return(df) below, it did not work. Now with the df in the following line, worked fine. Do you know why this second line is needed? – COLO Nov 02 '18 at 17:14
  • 1
    If you don't have an explicit `return()` call, then functions will output the value of the last evaluated expression. So your method without the final `df` should return just the value of `input$var`. See [here](https://www.datamentor.io/r-programming/return-function/) for a brief explanation of that and [here](https://stackoverflow.com/questions/11738823/explicitly-calling-return-in-a-function-or-not) for a discussion on whether or not to explicitly call `return(df)` or just `df` – Qwfqwf Nov 02 '18 at 20:06
0

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)
  })
Qwfqwf
  • 483
  • 3
  • 9