【发布时间】:2020-03-01 22:15:02
【问题描述】:
我正在尝试使用 lungDeaths 时间序列绘制 dyGraph,但我希望“mdeaths”和“fdeaths”位于辅助轴上,如果其中至少一个与“ldeaths”一起被选中。
这是一个工作示例:
global.R
library(dygraphs)
library(shiny)
library(datasets)
library(stringr)
lungDeaths <- cbind(mdeaths, fdeaths)
ui.R
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")
)
)
))
server.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。有没有什么方法可以在不必指定每种可能性的情况下做到这一点?
我已经研究了how to add dySeries based on input 以及如何做conditional evaluation when using pipes,但到目前为止我找到的答案对我不起作用。我通常会收到一条错误消息:
$ 运算符对原子向量无效
【问题讨论】:
标签: r shiny r-dygraphs