在这个miniapp中,目标是显示原始系列及其在所选范围内的平均值:
library(dygraphs)
library(datasets)
server <- function(input, output) {
reacteddata <- reactive({
dt = cbind(as.xts(ldeaths),ave=NA)
if (!is.null(input$dygraph_date_window)){
start=strftime(input$dygraph_date_window[[1]])
end=strftime(input$dygraph_date_window[[2]])
subset = window(as.xts(ldeaths), start=start, end=end)
ave = rep(mean(subset), length(subset))
dt[index(as.xts(subset)),"ave"] = ave
dt = dt[index(as.xts(subset))]
} else {
dt[,"ave"] = rep(mean(ldeaths), length(ldeaths))
}
dt
})
output$dygraph <- renderDygraph({
dygraph(reacteddata(), main = "Predicted Deaths/Month")
})
}
ui <- fluidPage(
sidebarLayout(
mainPanel(
dygraphOutput("dygraph")
)
)
)
shinyApp(ui = ui, server = server)
它可以工作,甚至可以重绘缩放上的平均线(使用鼠标选择缩放日期范围):
然而,问题是它在每次重绘时都会丢失数据,因此无法缩小。任何想法如何重做?
答案 0 :(得分:1)
有助于在dt
元素之外保留完整的reactive
数据集,并根据所选的被动ave
更新dygraph_date_window
(平均值)列。
此外,retainDateWindow
需要设置为TRUE
。
library(dygraphs); library(shiny); library(datasets); library(xts)
server <- function(input, output) {
dt = setNames(as.xts(ldeaths), "ldeaths")
dt = cbind(dt,ave=NA)
reacteddata <- reactive({
if (!is.null(input$dygraph_date_window)){
start=strftime(input$dygraph_date_window[[1]])
end=strftime(input$dygraph_date_window[[2]])
subset = window(dt, start=start, end=end)
ave = rep(mean(subset$ldeaths), nrow(subset))
dt[index(as.xts(subset)),"ave"] = ave
} else {
dt[,"ave"] = rep(mean(ldeaths), length(ldeaths))
}
dt
})
output$dygraph <- renderDygraph({
dygraph(reacteddata(), main = "Predicted Deaths/Month") %>%
dyOptions(retainDateWindow = TRUE)
})
}
ui <- fluidPage(
dygraphOutput("dygraph")
)
shinyApp(ui = ui, server = server)