替换控制派生值和用户选择值之间的sliderInput

时间:2015-06-03 21:03:16

标签: r shiny data-visualization

我有一个非常简单的Shiny应用程序,其中我有一组关于过去客户的数据,以及一组关于3个新客户的数据。我的所有数据仅包含2个变量:年龄和分数。

目的是从3个新客户中选择一个,看看过去的相似年龄的客户是如何得分的。我们使用简单的散点图来做到这一点。

例如,由于新客户#1已有30年历史,我们可以看到25岁至35岁的所有过去客户如何得分:

enter image description here

(我为小图片道歉)

一切正常。当我添加一个年龄滑块时,麻烦就开始了,其目的是允许用户覆盖新客户年龄后面提供的默认视图。

继续这个例子,假设我们很想知道过去18至40岁的客户如何得分,不再只是25岁至35岁。

不知何故,我需要实施一个两步过程:

  1. 数据子集需要BEGIN与硬编码+ - 5相对于所选新客户的年龄。
  2. NEXT - 数据的子集需要由UI上的滑块控制。
  3. 我面临着一个基本问题,就是告诉Shiny在不同的时间以两种不同的方式在UI和数据之间进行通信。关于如何解决这个问题的任何想法?

    要遵循的完整代码......但我在这里大声思考:我不知何故需要改变:

    subset_historic_customers <- reactive({ DF <- historic_customers[which((historic_customers$age >= get_selected_customer()$age-5) & (historic_customers$age <= get_selected_customer()$age+5)), ] return(DF) })

    subset_historic_customers <- reactive({ # start the same as above: DF <- historic_customers[which((historic_customers$age >= get_selected_customer()$age-5) & (historic_customers$age <= get_selected_customer()$age+5)), ] return(DF) # ...but if someone uses the age selection slider, then: DF <- historic_customers[which((historic_customers$age >= input$age[1]) & (historic_customers$age <= input$age[2])), ] })

    谢谢!

    app.R

    ## app.R ##
    server <- function(input, output) {
    
      new_customers <- data.frame(age=c(30, 35, 40), score=c(-1.80,  1.21, -0.07))
      historic_customers <- data.frame(age=sample(18:55, 500, replace=T), score=(rnorm(500)))
    
      get_selected_customer <- reactive({cust <- new_customers[input$cust_no, ]
                                         return(cust)})
    
    
      subset_historic_customers <- reactive({
        DF <- historic_customers[which((historic_customers$age >= get_selected_customer()$age-5) & (historic_customers$age <= get_selected_customer()$age+5)), ]
    #    DF <- historic_customers[which((historic_customers$age >= input$age[1]) & (historic_customers$age <= input$age[2])), ]
    
        return(DF)
        })
    
      output$distPlot <- renderPlot({
        plotme <<- subset_historic_customers()
        p <- ggplot(data=plotme, aes(x=plotme$age, y=plotme$score))+ geom_point()
        my_cust_age <- data.frame(get_selected_customer())
        p <- p + geom_vline(data=my_cust_age, aes(xintercept=age))
        print(p)
        })
    }
    
    ui <- fluidPage(
      sidebarLayout(
        sidebarPanel(
          numericInput(inputId="cust_no", label="Select new customer:", value=1),
          sliderInput(inputId="age", "Age of historic customer:", min=18, max = 55, value=c(18, 55), step=1, ticks=TRUE)
        ),
        mainPanel(plotOutput("distPlot"))
      )
    )
    
    shinyApp(ui = ui, server = server)
    

1 个答案:

答案 0 :(得分:1)

我相信这是你想要的代码。这不是太复杂,我希望它有所帮助

private