Clarinetist Clarinetist - 3 months ago 34
R Question

Conditioning on input variables and creating new variables in Shiny

ui.R:

library(shiny)

shinyUI(fluidPage(
checkboxGroupInput("Check1",label=h4 ("Coin Type:"), choices = c("Fair","Unfair (p = 60% for heads)"))
))


server.R:

library(shiny)

shinyServer(function(input, output) {
if (input$Check1 == "Fair"){
x <- 1
output$Value <- renderTable(as.data.frame(x))
} else {
x <- 5
output$Value <- renderTable(as.data.frame(x))
}
})


This should be very simple: there should be two check boxes. When "Fair" is checked, give
x
the value 1; otherwise, 5. Then display it on a data frame.

The problem, I think, is from assigning the variable
x
. Here is the error I get:

Warning: 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.)
Stack trace (innermost first):
44: .getReactiveEnvironment()$currentContext
43: .subset2(x, "impl")$get
42: $.reactivevalues
41: $ [-- this has a folder directory --]
40: server [-- this has a folder directory --]
1: runApp
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.)


[note that I omitted
41
and
40
above].

How do I deal with this problem? Searching has led me to nothing, and it isn't clear to me how to use
reactiveValues
.

Answer

You need to make x reactive to do what you want like so:

x <- reactive({
  if (input$Check1 == "Fair"){
  1
} else { 
  5  
}
# pass reactive x() to renderTable
output$Value <- renderTable(as.data.frame(x()))
Comments