Получить имена столбцов визуализированной таблицы DT - PullRequest
0 голосов
/ 18 октября 2018

Я взял на себя проект, который использует некоторую аккуратную функцию для удаления пустых / уродливых столбцов перед рендерингом с DT::renderDT().Значение ячейки в данном столбце может представлять другую таблицу, и я хотел бы сослаться на них.Поэтому, если пользователь щелкает ячейку, приложение должно отобразить другую таблицу с таким именем.Однако значения ячеек только однозначно связаны с другими таблицами в контексте имен столбцов. input$tbl_cell_clicked предоставляет только индексы, а не имена столбцов.Функция очистки может удалить пустые столбцы, поэтому я не могу полагаться на номера индексов.

Как получить текущие отображаемые имена столбцов таблицы?

  library(shiny)
  library(DT)
  shinyApp(
    ui = fluidPage(fluidRow(column(12, DTOutput('tbl')))),
    server = function(input, output) {
      output$tbl = renderDT(

        #I took over a project that uses some tidy functions to drop empty/ugly columns before rendering

        #column names and order therefore cannot be guranteed, here exemplified with use of sample()
        iris[,sample(ncol(iris),3)], options = list(lengthChange = FALSE)
      )

      #i need to know the cell value and column name of latest click gesture, not only index col
      observe({

        #how can I retrieve the column name that cell clicked was in?
        print(input$tbl_cell_clicked)

        #The rendered table iris[,sample(ncol(iris))] cannot be scoped from here

        #Don't wanna go down that road of <<- solutions
        #could be solved by dumping latest iris[,sample(ncol(iris),3)] into a reactive values,
        #but that might look messy to use extra lines to save metadata from latest rendered DT


      })
    }
  )

Ответы [ 2 ]

0 голосов
/ 11 июня 2019

Вот решение JavaScript.

library(shiny)
library(DT)

js <- c(
  "table.on('click', 'td', function(){",
  "  var cell = table.cell(this);",
  "  var colindex = cell.index().column;",
  "  var colname = table.column(colindex).header().innerText;",
  "  Shiny.setInputValue('column_clicked', colname);",
  "});"
)

shinyApp(
  ui = fluidPage(
    fluidRow(column(12), verbatimTextOutput("colclicked")),
    fluidRow(column(12, DTOutput('tbl')))
  ),

  server = function(input, output) {

    output$tbl = renderDT(
      iris[,sample(ncol(iris),3)], options = list(lengthChange = FALSE), 
      callback = JS(js)
    )

    output$colclicked <- renderPrint({
      input[["column_clicked"]]
    })
  }
)

enter image description here

0 голосов
/ 18 октября 2018

Реактивное задание может быть вставлено в функцию приближения.Тиди-функция выводит информацию непосредственно перед рендерингом в реактивное значение, содержащее имена столбцов последних визуализированных данных.

#some tidy function mentioned several times many different place in code
a_tidy_function = function(
  dt, #df or dt
  #added this argument to tidy function
  reactiveRef=NULL) {
  #tidy data.frame / data.table
  tidy_dt = dt[,sample(ncol(dt))]

  #include this line to update reactive value at reactiveRef
  if(!is.null(reactiveRef)) reactiveRef(colnames(tidy_dt)) #

  return(tidy_dt)
}

  library(shiny)
  library(DT)
  shinyApp(
    ui = fluidPage(fluidRow(column(12, DTOutput('tbl')))),
    server = function(input, output) {

      r_latest_column = reactiveVal()
      output$tbl = renderDT(

        #I took over a project that uses some tidy functions to drop empty/ugly columns before rendering

        #column names and order therefore cannot be guranteed, here exemplified with use of sample()
        {


        iris_rendered = a_tidy_function(
            iris,
            reactiveRef = r_latest_column) #col name info dumped to r_latest_column
        iris_rendered
        }, options = list(lengthChange = FALSE)

      )

      #i need to know the cell value and column name of latest click gesture, not only index col
      observe({

        #here are the value and indexes
        print(input$tbl_cell_clicked)

        #and... column names are now accesible here...
        print(r_latest_column())


      })
    }
  )

Как упоминает @hrbrmstr в комментарии, можно получить имена столбцов из javascript domaine, я попробовал это, и это показалось слишком громоздким для того, что я должен завершить сегодня, однако я нашел этот многообещающий учебник, который я сделаюсмотреть в ...

https://github.com/FrissAnalytics/shinyJsTutorials https://github.com/FrissAnalytics/shinyJsTutorials/tree/master/tutorials/materials3/messageApp2

...