I'm new to shiny, and I am trying to do a simple density plot where there are 2 groups of data, with reactive 'shifts' in the mean etc.
A simplified summary of this is that one set of data has a mean of 0, and variance of 1. The second set of data has a mean of shift
, which is defined in a slider.
I have tried to use reactiveValues
, as shown in the code below to store the matrix of observations d1
, generated from the density
function y values, and the corresponding x values are stored in x
.
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("shift",
"shift of 2nd set",
min = -1,
max = 1,
value = 0)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
data <- reactiveValues({
d1 <- matrix(nrow=100, ncol=512)
for(i in 1:70){
d1[i,] <- density(rnorm(1000),from = -3, to = 3)$y
}
for(i in 71:100){
d1[i,] <- density(rnorm(1000, input$shift),from = -3, to = 3)$y
}
x <- density(rnorm(1000),from = -3, to = 3)$x
})
output$distPlot <- renderPlot({
matplot(data$x, t(data$d1), type = "l", lty = 1, col = c(rep(1,70),rep(2,30)))
})
}
# Run the application
shinyApp(ui = ui, server = server)
The above code is largely from the example shiny app, so please excuse any generic references. It should still work.
I was expecting a shiny plot with a slider on the left, and a plot on the right with 100 density lines in 2 colours. When the shift
slider is changed the second set of data (red) will slide left or right depending on the shift.
Instead, I get the error message
55: stop
54: .getReactiveEnvironment()$currentContext
53: .subset2(x, "impl")$get
52: $.reactivevalues
47: server [/beavis/Documents/test/app.R#37]
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.)
Is anyone able to help me fix this code? Any help will be greatly appreciated. Having played around for an hour I believe the issue lies in the reactiveValues
section, but nothing so far has worked.