Reputation: 4995
With the following code a columns of a data.dable
can be selected.
mtcars_dt <- data.table(mtcars)
selected_cols <- c("mpg")
mtcars_dt[ ,..selected_cols]
I would like do the same within a reactive expressions in shiny. However, it behaves strangely. Here is a reproducible example
library(shiny)
library(data.table)
mtcars_dt <- data.table(mtcars)
ui <- basicPage(
selectInput("var", "Select variable", names(mtcars)),
textOutput("out1"),
textOutput("out2")
)
server <- function(input, output) {
output$out1 <- renderText({
mtcars[1:3 ,input$var]
})
output$out2 <- renderText({
mtcars_dt[1:3 , ..input$var]
})
}
shinyApp(ui, server)
When I run this app, the second output is a string with the name of the column I want to select.
Why is that happening? And how can I fix it?
Upvotes: 5
Views: 393
Reputation: 33510
Please check the following options:
library(shiny)
library(data.table)
mtcars_dt <- data.table(mtcars)
ui <- basicPage(
selectInput("var", "Select variable", names(mtcars)),
textOutput("out1"),
textOutput("out2")
)
server <- function(input, output) {
output$out1 <- renderText({
mtcars[1:3, input$var]
})
output$out2 <- renderText({
cols <- input$var
unlist(mtcars_dt[1:3, ..cols])
# 1. alternative
# mtcars_dt[1:3][[input$var]]
# 2. alternative
# mtcars_dt[1:3, get(input$var)]
# 3. alternative
# unlist(mtcars_dt[1:3, .SD, .SDcols = input$var])
# 4. alternative
# unlist(mtcars_dt[1:3, input$var, with = FALSE])
})
}
shinyApp(ui, server)
Upvotes: 2