Home > database >  Shiny: Use input$value containing column names within a lapply function to extract columns from list
Shiny: Use input$value containing column names within a lapply function to extract columns from list

Time:09-21

I am working on a shiny app which contains a list of dataframes (table_list) and below is a reactive function assignment from that app. There is an input value input$column_names which is a list of column names that correspond to the column names in table_list. I want to reactively select these columns within a lapply() function using the column names. Below is my failed attempt.

  Selected_column <- reactive({
    req(table_list())
    lapply(table_list, function(DT){
      DT$input$column_name
    })
  })

The line DT$input$column_name returns a NULL value. So my question is, how can I select a column of a given list dataframe based on a column name input?

CodePudding user response:

That's not specific to shiny. To access or extract a column from a dataframe (or a list or ... ) whose name is stored in a variable you have to use [[ instead of $.

For more see e.g. The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

column_name <- "mpg"

# Does not work
mtcars$column_name
#> NULL

# Works
mtcars[[column_name]]
#>  [1] 21.0 21.0 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 17.8 16.4 17.3 15.2 10.4
#> [16] 10.4 14.7 32.4 30.4 33.9 21.5 15.5 15.2 13.3 19.2 27.3 26.0 30.4 15.8 19.7
#> [31] 15.0 21.4

And a minimal shiny app based on the code snippet you provided:

library(shiny)

ui <- fluidPage(
  selectInput("column_name", "Select a column:", choices = names(mtcars)),
  tableOutput("selected")
)

server <- function(input, output, session) {
  table_list <- reactive(
    list(
      a = mtcars,
      b = mtcars
    )
  )

  Selected_column <- reactive({
    req(table_list())
    lapply(table_list(), function(DT) {
      DT[[input$column_name]]
    })
  })
  
  output$selected <- renderTable({
    head(rbind.data.frame(Selected_column()))
  })
}

shinyApp(ui, server)
#> 
#> Listening on http://127.0.0.1:8179

  • Related