我有一个非常简单的Shiny应用程序,其中我有一组关于过去客户的数据,以及一组关于3个新客户的数据。我的所有数据仅包含2个变量:年龄和分数。
目的是从3个新客户中选择一个,看看过去的相似年龄的客户是如何得分的。我们使用简单的散点图来做到这一点。
例如,由于新客户#1已有30年历史,我们可以看到25岁至35岁的所有过去客户如何得分:
(我为小图片道歉)
一切正常。当我添加一个年龄滑块时,麻烦就开始了,其目的是允许用户覆盖新客户年龄后面提供的默认视图。
继续这个例子,假设我们很想知道过去18至40岁的客户如何得分,不再只是25岁至35岁。
不知何故,我需要实施一个两步过程:
我面临着一个基本问题,就是告诉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)
答案 0 :(得分:1)
我相信这是你想要的代码。这不是太复杂,我希望它有所帮助
private