簡體   English   中英

Shiny:使用 input$value 包含 lapply function 中的列名從列表數據幀中提取列

[英]Shiny: Use input$value containing column names within a lapply function to extract columns from list dataframes

我正在開發一個 shiny 應用程序,其中包含一個數據幀列表( table_list ),下面是來自該應用程序的反應式 function 分配。 有一個輸入值input$column_names是與table_list中的列名相對應的列名列表。 我想使用列名在lapply() function 中反應性地 select 這些列。 以下是我失敗的嘗試。

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

DT$input$column_name行返回 NULL 值。 所以我的問題是,如何根據列名輸入 select 給定列表 dataframe 的列?

這並不特定於 shiny。 要從名稱存儲在變量中的 dataframe(或list或...)中訪問或提取列,您必須使用[[而不是$

有關更多信息,請參見例如括號 [] 和雙括號 [[]] 之間的區別,用於訪問列表或 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

以及基於您提供的代碼段的最小 shiny 應用程序:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM