What kind of object is this, reactive?

放肆的年华 提交于 2020-01-15 05:05:24

问题


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 ?


回答1:


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"


来源:https://stackoverflow.com/questions/40335977/what-kind-of-object-is-this-reactive

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!