select 입력 추가하기
Shiny 앱에 입력을 추가하는 과정은 두 단계로 이루어져 있어요. 먼저 UI에 ___Input("x") 함수를 추가하고, 서버에서 input$x로 그 값을 가져오면 됩니다.
예를 들어, 사용자가 목록에서 동물을 고르게 하려면 selectInput을 사용할 수 있고, 선택된 값은 input$animal로 참조해요:
selectInput(
'animal',
'Select Animal',
selected = 'Cat',
choices = c('Dog', 'Cat')
)
이번 연습에서는 사용자가 성별을 선택할 수 있는 입력을 추가해, 성별별로 인기 상위 10개 이름을 시각화하는 Shiny 앱을 만들어 볼 거예요.
이 연습은 강의의 일부입니다
R로 Shiny 웹 애플리케이션 만들기
연습 안내
- "sex"라는 이름의 select 입력을 추가해 사용자가 "M"과 "F" 중에서 선택할 수 있게 하되, 기본값은 "F"로 설정하세요.
- 서버 코드를 업데이트해, 항상 "F"만 사용하지 말고 선택된 성별의 상위 10개 이름을 가져오도록 하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
ui <- fluidPage(
titlePanel("What's in a Name?"),
# CODE BELOW: Add select input named "sex" to choose between "M" and "F"
# 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 %>%
# MODIFY CODE BELOW: Filter for the selected sex
filter(sex == "F") %>%
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)