如果在Shiny服务器中的条件

时间:2017-09-20 17:08:38

标签: r if-statement shiny reactive

我试图根据输入操作数据帧。这是我的代码:

library(shiny)
library(quantmod)
ui <- fluidPage(
  plotOutput("chart", click = "SD1"),
  radioButtons(
    "term",
    "Term",
    choices = c("Daily", "Weekly", "Monthly"),
  ))

server <- function(input, output){
  df1 <- reactive(getSymbols("JPM", src = "google", auto.assign = F))
  output$chart <- renderPlot(
    if (input$term == "Weekly") {
      df <- to.weekly(df1())
    }
    else if (input$term == "Monthly") {
      df <- to.monthly(df1())
    }
    else {
      df <- df1()
    }
    chartSeries(
      df()
    )
  )
}

shinyApp(ui, server)

那么为什么我的条件不起作用?非常感谢你!

1 个答案:

答案 0 :(得分:3)

我认为你的括号混乱,这应该做的工作。如果您想要使用子集数据并仍然可以访问原始数据,则可以创建两个被动反应:您可以使用df1()访问其中一个,另一个是df()

library(shiny)
library(quantmod)

ui <- fluidPage(
  plotOutput("chart", click = "SD1"),
  radioButtons(
    "term",
    "Term",
    choices = c("Daily", "Weekly", "Monthly"),
  ))

server <- function(input, output){
  df1 <- reactive({getSymbols("JPM", src = "google", auto.assign = F)})

  df <-reactive({
    if (input$term == "Weekly") {
      df <- to.weekly(df1())
    }
    else if (input$term == "Monthly") {
      df <- to.monthly(df1())
    }
    else {
      df <- df1()
    }
    return(df)
  })

  output$chart <- renderPlot({

    chartSeries(df())
  })
}

shinyApp(ui, server)