仅在R Shiny app

时间:2018-02-12 17:03:11

标签: r shiny

我正在为不同的实验运行创建一个用于数据探索的R Shiny应用程序。我有不同的sliderInputselectInput来处理正在绘制的数据范围和变量。数据是通过API调用私有数据库获得的。

CODE

ui <- fluidPage(
  sliderInput(inputId = "num",
              label = "Experiment Id",
              value = 5, min = 2, max = 7),
  selectInput("x", "Horizontal Axis", colopts), #colopts is predefined 
  selectInput("y", "Vertical Axis", colopts), #colopts is predefined 
  plotOutput("userPlot")
)

server <- function(input, output){
  output$userPlot <- renderPlot({
    # testdata is a function that makes the API call, performs cleanup, calculations etc. 
    # The output is a list, the first element of which is being called here
    dat <- testdata(input$num)[[1]]
    # "type" is hard-coded for testing - to be changed later
    plt <- ggplot(dat, aes_string(x = input$x, y = input$y)) + 
      geom_point(aes(color = type ,fill = type, shape = type))+ 
      geom_line(aes(color = type)) + 
      ggtitle(paste("Test",input$num, sep = " "))
    return(plt)
  })

}

shinyApp(ui = ui, server = server)

输出

Current State

它工作正常,但是,每次我选择一个不同的变量来绘制任一轴时,代码会进行另一个API调用 - 这是预期的行为。由于绘制的数据集仅在选择了不同的实验ID时才会更改,因此我希望仅在更改实验ID时才进行API调用。

没有将整个数据集加载到内存中然后使用应用程序,有没有办法实现这一点,即如果只保留实验ID相同的轴更改,更新绘图而不进行API调用?

1 个答案:

答案 0 :(得分:2)

正如MrFlick在评论中所说,你可以使用依赖于input$num的被动反应,并使你的情节依赖于被动反应。这样做时,input$xinput$y发生变化时,只有情节无效,而被动反应保持不变,因为这仅取决于input$num。如果您更改了input$num,则无效的情节都会失效。

我根据您的代码创建了一个工作示例。新数据仅创建input$num更改,您可以从图中生成的数据的平均值中看到。

希望这有帮助!

library(shiny)
library(ggplot2)
set.seed(1)

ui <- fluidPage(
  sliderInput(inputId = "num",
              label = "Experiment Id",
              value = 5, min = 2, max = 7),
  selectInput("x", "Horizontal Axis", letters[1:3]), #colopts is predefined 
  selectInput("y", "Vertical Axis", letters[1:3]), #colopts is predefined 
  plotOutput("userPlot")
)

server <- function(input, output){

  # API call in here
  dat <- reactive({
    df = data.frame(a=rnorm(200,input$num,0.5),
                    b=rnorm(200,input$num,0.5),
                    c=rnorm(200,input$num,0.5),
                    type=sample(letters[10:15],100,replace = T))
  })

  output$userPlot <- renderPlot({
    # testdata is a function that makes the API call, performs cleanup, calculations etc. 
    # The output is a list, the first element of which is being called here
    # "type" is hard-coded for testing - to be changed later
    plt <- ggplot(dat(), aes_string(x = input$x, y = input$y)) + 
      geom_point(aes(color = type ,fill = type, shape = type)) + 
      geom_line(aes(color = type)) + 
      ggtitle(paste("Test",input$num, sep = " "))
    return(plt)
  })

}

shinyApp(ui = ui, server = server)