我是新手,我正在尝试做一个简单的密度图,其中有2组数据,平均值带有反应性“偏移”等。
对此的简化总结是,一组数据的平均值为0,方差为1。第二组数据的平均值为shift
,在滑块中定义。
我尝试使用reactiveValues
,如下面的代码所示,以存储从d1
函数y值生成的观测矩阵density
,并且相应的x值是存储在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)
上面的代码主要来自示例闪亮应用程序,因此请原谅任何通用引用。 应该仍然可以使用。
我期待的是一个明亮的情节,左边有一个滑块,而右边的情节有2种颜色的100条密度线。更改shift
滑块后,第二组数据(红色)将根据移位向左或向右滑动。
相反,我收到错误消息
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.)
有人可以帮助我修复此代码吗?任何帮助将不胜感激。玩了一个小时,我相信问题出在reactiveValues
部分,但是到目前为止没有任何效果。
答案 0 :(得分:3)
很好尝试。你很亲密您缺少的是两件事。您正在创建一个data
对象,该对象将成为反应对象(我改用reactive
)。这意味着每当您呼叫data
时,都需要将其称为data()
。
第二,您的data
仅返回x
。在您的情况下,此反应性环境的输出应为x
和d1
的列表。
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,
step = 0.1) # I added a step
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
# This reactive environment can be accessed using data().
data <- reactive({
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
list(x = x, d1 = d1) # make sure that all objects are returned
})
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)