Mickey_NC Mickey_NC - 1 month ago 11
R Question

What kind of object is this, reactive?

I have this code in my Server.R :

selection1 <- reactive({filter(filter(DF1, PC %in% input$dynamic),
AGE >= input$age[1] & AGE <= input$age[2])})


DF1
is a data frame object of course,
input$dynamic
is a checkboxGroupInput and
input$age
is a slider input. But what kind of object is
selection1
? Is it a data frame too ?

Then I would have liked to count the number of unique occurrences in variable
COMMUN
in
selection1
, so I tried this :

selection2 <- length(unique(selection1$COMMUN))


But I have this error message :


Warning: Error in $: object of type 'closure' is not subsettable


How can I do this operation please ?

Answer

selection1 is a reactive function. In Shiny this means it is a function that holds/caches your data. The data it holds is updated when you call the function AND when the inputs to it change. If the inputs haven't changed when you call it, it returns the cached data.

To access the data you need to call the function itself using selection1(), and then follow this with the usual functions/code for subsetting the data. So in your case it would be

selection2 <- length(unique(selection1()$COLUMN))

The error you're seeing is the standard error when you try to perform the $ operation on a function, without calling the function using ()

foo <- function(){
    bar = data.frame(bar = c(1,2,3))
}

foo$bar
Error in foo$bar : object of type 'closure' is not subsettable

foo()$bar
[1] 1 2 3

If you want to go into the actual detail of the structure of a reactive object, just call str on it and take a look

foo <- reactive()

str(foo)

function ()  
 - attr(*, "observable")=Classes 'Observable', 'R6' <Observable>
  Public:
    .dependents: environment
    .domain: NULL
    .error: FALSE
    .execCount: 0
    .func: function (...) 
    .invalidated: TRUE
    .label: foo
    .mostRecentCtxId: 
    .running: FALSE
    .updateValue: function () 
    .value: NULL
    .visible: 
    clone: function (deep = FALSE) 
    getValue: function () 
    initialize: function (func, label = deparse(substitute(func)), domain = getDefaultReactiveDomain(), 
    self: Observable, R6 
 - attr(*, "class")= chr "reactive"