建立一些輔助函式
在 shinydashboard 中可以加入許多元素。若要讓使用者輸入與儀表板輸出之間產生互動,你需要在伺服端中放置的 render 函式裡定義這些互動。
當互動與輸出很多時,程式碼很快就會變得難以維護。解法之一是於 shinydashboard 環境之外,建立你自己的輔助函式。
接下來,你會建立兩個輔助函式:
num_listings():依據price範圍內的篩選資料,回傳房源數量。make_plots():根據使用者選擇,以及price範圍內的篩選資料,繪製盒狀圖或小提琴圖。
已載入 listings,並已匯入 sf、tidyverse 與 leaflet。
本練習屬於課程
使用 shinydashboard 建立儀表板
練習說明
- 篩選
listings,使其限制在引數range(為 shinyApp 輸入的佔位符)的左右界限之間。 - 設定正確的 if-else 條件:當
choice等於"Box plots"時繪製盒狀圖;當為"Violin plots"時繪製小提琴圖。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
num_listings <- function(range){
# Filter listings appropriately
filter(listings, price >= ___, price <= ___) %>% nrow()
}
make_plots <- function(range, choice){
filtered_listings <- filter(listings, price >= range[1], price <= range[2])
# Set the correct if-else conditions
if (choice == ___){
filtered_listings %>%
ggplot(aes(y = price, x = room_type)) + geom_boxplot() + theme_classic()
}
else if (___){
filtered_listings %>%
ggplot(aes(y = price, x = room_type)) + geom_violin() + theme_classic()
}}