简体   繁体   中英

How to use data.table in a reactive expression in shiny?

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM