I have a data set spanning several years. My shiny app is intended to let the user step through one week at a time, do some analysis and update the data set with new information for that week. e.g. the schedule.
In normal R, I do the following code, where update_schedule is a custom function:
data[indx:(indx+7)] <- update_data(data[indx:(indx+7)], schedule)
Using shiny, I am trying to do something similar, but getting the error:
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.)
#ui
shinyUI(pageWithSidebar(
sidebarPanel(
actionButton("nextButton", "Process Next Week")
),
mainPanel(
textOutput('week'),
plotOutput('myplot')
)
))
#server
data <<- data.frame(value = rep(1:4, 3:6), open = rep(c(1,1,0), 6))
shinyServer(function(input, output) ({
week <- reactive({as.numeric(input$nextButton)+1})
output$week <- renderText({week()})
#this is the problem line
data[(week()*7):((week()+1)*7)]$open <<- rep(1,7)
#but here the sub-setting works for plotting
output$myplot <- renderPlot({
p1 <- plot(data$value[(week()*7):((week()+1)*7)],
col = as.factor(data$open)[(week()*7):((week()+1)*7)])
return(p1)
})
})
)
Is there a way to use the week() value to select a portion of data to update? Also, in reality I am trying to update several variables at once, not just the "open" column in this example.
I tried the following to keep my reactive variables in a reactive statement, but got an error:
data <<- reactive({data %>%
mutate(open = replace(open, (week()*7):((week()+1)*7, rep(1,7))})
Error in plot(data()$value[(week() * 7):((week() + 1) * 7)], col = as.factor(data()$open)[(week() * :
error in evaluating the argument 'x' in selecting a method for function 'plot': Error in UseMethod("mutate_") :
no applicable method for 'mutate_' applied to an object of class "reactive"
Did you read and fully understand the reactive expressions chapter of the shiny tutorial? http://shiny.rstudio.com/tutorial/lesson6/
Any expression that uses a reactive expression (
week
is reactive since you define it with areactive({})
must be used inside a reactive context, such as anotherreactive()
call or insideobserve
orrenderXXX
. You should also look atreactiveValues()
function