我正在尝试使用lungDeaths时间序列绘制一个dyGraph,但我希望“mdeaths”和“fdeaths”位于辅助轴上,如果其中至少一个与“ldeaths”一起被选中。
这是一个工作示例:
全局.R
library(dygraphs)
library(shiny)
library(datasets)
library(stringr)
lungDeaths <- cbind(mdeaths, fdeaths)
用户界面
shinyUI(fluidPage(
titlePanel("Predicted Deaths from Lung Disease (UK)"),
sidebarLayout(
sidebarPanel(
id="sidebar", width = 3,
div(
checkboxGroupInput(
inputId = "selection", label = "Variables:",
choiceNames = list("ldeaths",
strong("mdeaths"),
strong("fdeaths")
),
choiceValues = c("ldeaths",
"mdeaths",
"fdeaths"), selected = "ldeaths"),
uiOutput("rendered"),
style = "font-size:75%"
)
),
mainPanel(
dygraphOutput("dygraph")
)
)
))
服务器.R
shinyServer(function(input, output) {
lungDeaths <- cbind(mdeaths, fdeaths, ldeaths)
rData <- reactive({
rData <- ts(lungDeaths[,input$selection])
})
output$dygraph <- renderDygraph({
if(length(input$selection) > 1 & length(str_subset(input$selection, 'ldeaths$'))>0){
if(length(str_subset(input$selection, 'fdeaths$'))>0 & length(str_subset(input$selection, 'mdeaths$'))>0){
dygraph(rData(), main = "Deaths from Lung Disease (UK)") %>%
dySeries("mdeaths", axis = 'y2') %>%
dySeries("fdeaths", axis = 'y2')
}
else if(length(str_subset(input$selection, 'mdeaths$'))>0){
dygraph(rData(), main = "Deaths from Lung Disease (UK)") %>%
dySeries("mdeaths", axis = 'y2')
}
else if(length(str_subset(input$selection, 'fdeaths$'))>0){
dygraph(rData(), main = "Deaths from Lung Disease (UK)") %>%
dySeries("fdeaths", axis = 'y2')
}
}
else
dygraph(rData(), main = "Deaths from Lung Disease (UK)")
})
})
这段代码做了我想做的事,但我想避免使用这么多的 if 和 else,因为我实际使用的项目有 6 个项目在选择时应该转到 y2。有没有办法在不必指定每种可能性的情况下做到这一点?
我已经研究过如何根据输入添加 dySeries以及如何在使用管道时进行条件评估,但到目前为止我发现的答案对我不起作用。我通常会收到一条错误消息:
$ 运算符对原子向量无效