BDuff
BDuff

Reputation: 29

How to call a reactive variable in R shiny using svytable

I set up this reactive variable in shiny.

  v <- reactive({
    var <- switch(input$var,
                   Centers = centers,
                   Homes = homes,
                   homes)

which references these two survey design objects, created from unweighted, subsetted data.

centers <- svydesign(id=~HH9_METH_VPSUPU,
                           strata=~HH9_METH_VSTRATUMPU,
                           weights=~HH9_METH_WEIGHT,
                           data=ucenters)

homes <- svydesign(id=~HH9_METH_VPSUPU,
                     strata=~HH9_METH_VSTRATUMPU,
                     weights=~HH9_METH_WEIGHT,
                     data=uhomes)

However, I'm having mixed results referencing them in waffle graphs in tabPanels. In the wvals line below...

  # Flexibility ----
  output$C14A_5 <- renderPlot({
    wvals <- round((as.data.frame(prop.table((svytable(~v()$variables$HH9_C14A_5_FLEX, v()))))$Freq*100), digits = 0)
    val_names <- sprintf("%s (%s)", vallabels, scales::percent(round(wvals/sum(wvals), 2)))
    names(wvals) <- val_names
    waffle::waffle(wvals, title="Importance of flexibility")
  })

I'm able to get away with the second instance of v(), in the design field, but the first instance gives me a "could not find function "v"" error.

In that same instance, I have also tried svytable(~v[['variables']][['HH9_C14A_5_FLEX']], but that tells me "object 'v' not found."

I have also tried specifying this outside of the call, like below...

  # Flexibility ----
  output$C14A_5 <- renderPlot({
    dataset <- v()
    wvals <- round((as.data.frame(prop.table((svytable(~dataset()$variables$HH9_C14A_5_FLEX, v()))))$Freq*100), digits = 0)
    val_names <- sprintf("%s (%s)", vallabels, scales::percent(round(wvals/sum(wvals), 2)))
    names(wvals) <- val_names
    waffle::waffle(wvals, title="Importance of flexibility")
  })

But that gives me "object 'dataset' not found." That's the same if I try it with [[ rather than $, obviously.

I've also tried using paste0, but I have the same trouble as above.

Anything else I can try? Is there another way to call a reactive variable where I can call on its features? Surely there's a way to do this!

Upvotes: 0

Views: 79

Answers (1)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84529

Use a character string and as.formula to convert it to a formula.

For example, the formula ~x is the same as as.formula("~x").

So if you have a string in a reactive variable X you can do as.formula(paste0("~", X())).

Upvotes: 1

Related Questions