연도를 선택하는 슬라이더 입력 추가
슬라이더 입력은 숫자 입력에 매우 유용해요. 사용자가 값의 범위에서 선택하도록 할 때도, 고정된 옵션 집합에서 하나를 고르게 하되 selectInput()보다 더 직관적인 방식을 쓰고 싶을 때도 좋습니다.
babynames에 있는 연도 중 하나를 선택할 수 있도록 슬라이더를 추가해서, 특정 연도의 상위 10개 이름을 표시하는 앱으로 수정해 보세요.
이 연습은 강의의 일부입니다
R로 Shiny 웹 애플리케이션 만들기
연습 안내
- 사용자가 1900년부터 2010년 사이의 연도를 선택할 수 있도록 이름이 "year"인 슬라이더 입력을 추가하고, 기본값은 1900으로 설정하세요.
- 서버 코드를 업데이트하여 1900년만이 아니라 선택한 연도의 상위 10개 이름을 가져오도록 하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
ui <- fluidPage(
titlePanel("What's in a Name?"),
# Add select input named "sex" to choose between "M" and "F"
selectInput('sex', 'Select Sex', choices = c("F", "M")),
# CODE BELOW: Add slider input named 'year' to select years (1900 - 2010)
# Add plot output to display top 10 most popular names
plotOutput('plot_top_10_names')
)
server <- function(input, output, session){
# Render plot of top 10 most popular names
output$plot_top_10_names <- renderPlot({
# Get top 10 names by sex and year
top_10_names <- babynames %>%
filter(sex == input$sex) %>%
# MODIFY CODE BELOW: Filter for the selected year
filter(year == 1900) %>%
slice_max(prop, n = 10)
# Plot top 10 names by sex and year
ggplot(top_10_names, aes(x = name, y = prop)) +
geom_col(fill = "#263e63")
})
}
shinyApp(ui = ui, server = server)