我正在使用Dygraphs包来实现R闪亮的实际和时间序列预测值的可视化。这是我用来生成Dygraph的示例代码。在某些情况下,数据点较少Holt Winters(gamma = T)没有给出任何预测,我需要显示标题为“数据不足”的空Dygraph。我无法做到这一点。感谢您对此的任何帮助
library(dygraphs)
plotDyg <- fluidPage(
fluidRow(
box(selectizeInput("c1", "Enter a key",
choices = reactive({sort(unique(df$key))})(),
multiple = FALSE),width=3),
box(dygraphOutput("tsDy"), width = 10, height = 500))
)
ui <- dashboardPage(
dashboardHeader(title = "XYZ"),
dashboardSidebar(
sidebarMenu(
menuItem("abc", tabName = "sidebar2", icon = icon("bar-chart") ,
menuSubItem("def",icon = icon("folder-open"), tabName = "subMenu1")
)
)
),
dashboardBody(
tabItems(
tabItem(tabName = "subMenu1",
fluidRow(
tabBox(
title = "ghi", id = "tabset2",height = "1500px",width = 100,
tabPanel("abcdef", plotDyg)
)
)
)
)
)
)
server <- function(input, output) {
output$tsDy <- renderDygraph({
if(!is.null(input$c1)){
df.0 <- reactive({df[df$key == input$c1,]})()
tspred <- reactive({
df.0 <- convert_to_ts(df.0) # converts column "fin_var" to a monthly time series and returns the entire dataframe
act <- df.0$fin_var
hw <- tryCatch(HoltWinters(df.0$fin_var), error=function(e)NA)
if(length(hw) > 1){
p <- predict(hw, n.ahead = 12, prediction.interval = TRUE, level = 0.95)
all1 <- cbind(act, p)
}else{all1 <- matrix()}
})
if(!is.na(tspred())){
dygraph(tspred(), main = "TS Predictions") %>%
dySeries("act", label = "Actual") %>%
dySeries(c("p.lwr", "p.fit", "p.upr"), label = "Predicted") %>%
dyOptions(drawGrid = F) %>%
dyRangeSelector()
}else{dygraph(matrix(0), main = "Insufficient Data")} # I could just do 'return()' but I want to show an empty Dygraph with the title
}else{return()}
})
}
答案 0 :(得分:1)
我也无法用空的时间序列渲染Dygraphs。为了向用户呈现消息,我使用了validate/need functions in Shiny
在您的情况下,我将替换
if(!is.na(tspred())){
使用
validate(need(!is.na(tspred())), "Insufficient Data"))
这将避免Dygraphs中出现“错误:参数长度为零”消息,并向最终用户打印适当的消息。