【发布时间】:2015-08-18 06:53:35
【问题描述】:
我有一个非常简单的 Shiny 应用程序,其中我有一组关于过去客户的数据,以及一组关于 3 个新客户的数据。我的所有数据仅包含 2 个变量:年龄和分数。
目的是从3个新客户中选择一个,看看过去年龄相近的客户的得分情况。我们用一个简单的散点图来做到这一点。
例如,由于新客户 #1 是 30 岁,我们可以查看所有 25 - 35 岁的过去客户的得分:
(我为小图道歉)
一切正常。当我添加一个年龄滑块以允许用户覆盖新客户年龄在幕后提供的默认视图时,问题就开始了。
继续这个例子,假设我们很想知道过去的客户(例如 18 至 40 岁,而不仅仅是 25 至 35 岁)的得分。
不知何故,我需要实现一个两步过程:
- 数据的子集需要以相对于所选新客户年龄的硬编码 +- 5 开始。
- NEXT -- 数据的子集需要由 UI 上的滑块控制。
我面临一个基本问题,即告诉 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)
【问题讨论】:
-
每次选择新客户时,如果您只是将滑块值更新为客户的 +/- 5,它不会正常工作吗?并告诉情节始终遵循滑块所说的内容?
-
是的!这是最难的部分!这在技术上具有挑战性,至少对我来说是这样。
标签: r shiny data-visualization