添加年份筛选:数值滑块输入
滑块输入与数值输入用途相近,因为二者都让用户可以选择一个数字。
如果滑块的初始值(value 参数)是单个数字,则滑块用于选择单个数值。而如果初始值是由两个数字组成的向量,则滑块将用于选择「两个数值」,而不仅仅是一个值。
我们已经看到,不同的输入可能有不同的参数。要记住每个输入使用的确切参数并不容易。想要了解某个输入函数可以使用哪些参数,唯一的方法就是查看它的文档或帮助文件。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
- 在 UI 中添加一个
sliderInput(),ID 为 "years",标签为 "Years"(第 14 行)。- 将最小值设为数据集中最早的年份,最大值设为数据集中最晚的年份。
- 默认情况下,将滑块的端点设为 1977 和 2002,这样只显示介于这两个年份之间(包含端点)的数据。
- 在服务器端添加代码,使输入中选择的年份用于对
gapminder数据进行子集筛选,只显示这些年份范围内的记录(第 28 行)。
交互式实操练习
通过完成这段示例代码来试试这个练习。
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("title", "Title", "GDP vs life exp"),
numericInput("size", "Point size", 1, 1),
checkboxInput("fit", "Add line of best fit", FALSE),
radioButtons("color", "Point color",
choices = c("blue", "red", "green", "black")),
selectInput("continents", "Continents",
choices = levels(gapminder$continent),
multiple = TRUE,
selected = "Europe"),
# Add a slider selector for years to filter
___("years", ___, ___, ___, ___)
),
mainPanel(
plotOutput("plot")
)
)
)
# Define the server logic
server <- function(input, output) {
output$plot <- renderPlot({
# Subset the gapminder data by the chosen years
data <- subset(gapminder,
continent %in% input$continents &
year >= ___$years[1] & year <= ___$years[2])
p <- ggplot(data, aes(gdpPercap, lifeExp)) +
geom_point(size = input$size, col = input$color) +
scale_x_log10() +
ggtitle(input$title)
if (input$fit) {
p <- p + geom_smooth(method = "lm")
}
p
})
}
shinyApp(ui = ui, server = server)