How do I coerce contents of a reactive to a data.f

2019-09-14 18:40发布

问题:

I am having a lot of trouble adopting a good flow of object types as a shiny R reactive object is structured and moves data through my app. This is especially true if I am trying to dplyr::filter() a reactive's contents and return them to a base::data.frame or DT::data.table.

I see a lot of suggestion to "just to df()$element like any closure," but in a lot of cases (like Highcharter or using %in% to check sets) I have to store (df <- df()) before I can use x %in% df...

Say I have

> foo <- reactiveValues()
> str(foo)
List of 3
 $ impl    :Classes 'ReactiveValues', 'R6' <ReactiveValues>
  Public:
    .allValuesDeps: environment
    .dependents: environment
    .label: reactiveValues8306
    .metadata: environment
    .namesDeps: environment
    .setLabel: function (label) 
    .values: environment
    .valuesDeps: environment
    clone: function (deep = FALSE) 
    freeze: function (key) 
    get: function (key) 
    getMeta: function (key, metaKey) 
    initialize: function () 
    isFrozen: function (key) 
    mset: function (lst) 
    names: function () 
    self: ReactiveValues, R6
    set: function (key, value) 
    setMeta: function (key, metaKey, value) 
    thaw: function (key) 
    toList: function (all.names = FALSE)  
 $ readonly: logi FALSE
 $ ns      :function (x)  
 - attr(*, "class")= chr "reactivevalues"

I can store a data.frame in this reactive, as I do often when filtering:

> foo$config <- data.frame(a = c(1,2,3), b = c(4,5,6))

But, now I can only get myself in trouble:

> foo()
Error: could not find function "foo"
> foo$config
Error in .getReactiveEnvironment()$currentContext() : 
  Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)
> foo()$config
Error: could not find function "foo"

Usually at this point in the shiny-app building process I resort to trying to strong-arm the object into the form I want. Checking that object with renderPrints of calls to typeof() and class() usually tell me it is the object I'm looking for ("list", "data.table", or "data.frame") but the object will usually not conform then to the expected output of calls to renderDataTable or the aesthetic mappings in graphing libraries like ggplot or highcharter.

Can someone give me a better idea of what is going on? Related question here.