首页 > 解决方案 > How to extract values from data that are imported using ReactiveFileReader?

问题描述

I load data using the reactiveFileReader, and wanted to extract values like column names to use it in the tableHeader function. However, I don't understand how can I use the data on its own without going through render* function. Can someone assist?

    reactive_api_data <- reactiveFileReader(
        intervalMillis = 1000,
        session = session, 
        filePath = "data/data.csv",
        readFunc = read_csv
    )

    sketch <- htmltools::withTags(table(
        tableHeader(c("date", "a", "b", "c", "d", "e", "f", "g")), 
        tableFooter(c("Total",0,0,0,0,0,0,0))
    ))

    output$data_2019 <- DT::renderDataTable({ 
        reactive_api_data() %>% 
            filter(date > "2019-01-01")
    }, 
    container = sketch, 
    rownames = FALSE,
    options = list(paging = FALSE, searching = FALSE, lengthMenu = FALSE,
                      footerCallback = JS(
                          "function(row, data, start, end, display) {",
                          "var api = this.api(), data;",
                          "total = api.column(2).data().reduce( function(a, b) { return a + b }, 0);",
                          "$( api.column(2).footer() ).html(total);",
                          "}"
                          )
                      )

I would like to do something like

tableHeader(colnames(data))

instead of manually typing the column names, like this in my above code:

tableHeader(c("date", "a", "b", "c", "d", "e", "f", "g"))

标签: rshinydatatablesshiny-reactivity

解决方案


我将其更改sketch为要在 renderDataTable 中调用的反应函数。

reactive_api_data <- reactiveFileReader(
        intervalMillis = 1000,
        session = session, 
        filePath = "data/data.csv",
        readFunc = read_csv
    )

sketch <- reactive({ 
        htmltools::withTags(
            table(
                DT::tableHeader(colnames(reactive_api_data())), 
                DT::tableFooter(c("Total",0,0,0,0,0,0,0))
            )
        )
    })

output$data_2019 <- DT::renderDataTable({ 
        reactive_api_data() %>% 
            filter(date > "2019-01-01")
    }, 
    container = sketch(), 
    rownames = FALSE,
    options = list(paging = FALSE, searching = FALSE, lengthMenu = FALSE,
        footerCallback = JS(
            "function(row, data, start, end, display) {",
            "var api = this.api(), data;",
            "total = api.column(2).data().reduce( function(a, b) { return a + b }, 0);",
            "$( api.column(2).footer() ).html(total);",
            "}"
        )
    )

推荐阅读