Bắt đầu ngayBắt đầu miễn phí

Biến Dataframe thành reactive

Bây giờ hãy để dataframe của chúng ta thay đổi theo đầu vào của người dùng.

Bài tập này là một phần của khóa học

Xây dựng Dashboard với flexdashboard

Xem khóa học

Hướng dẫn bài tập

  • Tạo một "dataframe" reactive tên là show_trips_df chỉ chứa các chuyến có thời gian bắt đầu nằm trong khoảng người dùng chọn (bao gồm cả hai đầu). Đặt đoạn mã này chung một chunk với sliderInput() để gọn gàng.
  • Chạy tài liệu và thay đổi các đầu vào. Quan sát điều gì xảy ra (hoặc không xảy ra).

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

{"my_document.Rmd":"---\ntitle: \"Bike Shares Daily\"\noutput: \n  flexdashboard::flex_dashboard:\n    orientation: columns\n    vertical_layout: fill\nruntime: shiny\n---\n\n```{r global, include=FALSE}\nlibrary(flexdashboard)\nlibrary(readr)\nlibrary(leaflet)\nlibrary(DT)\nlibrary(tidyverse)\nlibrary(lubridate)\nlibrary(plotly)\n\ntrips_df <- read_csv('https://assets.datacamp.com/production/course_6961/datasets/sanfran_bikeshare_joined_oneday.csv') %>%\n  mutate(duration_min = duration_sec / 60,\n         start_hour = hour(start_date)) %>%\n  filter(duration_min <= 8 * 60) # remove trips longer than 8 hours as suspicious data quality\n\n```\n\n\n\nColumn {data-width=200 .sidebar}\n-----------------------------------------------------------------------\n\n```{r}\nsliderInput(\"start_slider\", \n            label = \"Select trip start times to display (hour of day):\",\n            min = 0, \n            max = 24, \n            value = c(7,10), \n            step = 1)\n\nshow_trips_df <- ___({\n  ___ %>%\n    filter(start_hour >= ___ &\n             start_hour <= ___)\n})\n```\n\nColumn {data-width=450}\n-----------------------------------------------------------------------\n### Origins\n\n```{r}\n\n  trips_df %>%\n    rename(latitude = start_latitude,\n           longitude = start_longitude) %>%\n    group_by(start_station_id, latitude, longitude) %>%\n    count() %>%\n    leaflet() %>%\n    addTiles() %>%\n    addCircles(radius = ~n)\n\n\n```\n\nColumn {data-width=350}\n-----------------------------------------------------------------------\n\n### Total Trips\n\n```{r}\n\nvalueBox(prettyNum(trips_df %>%\n                     nrow(), big.mark = ','), \n         icon = 'fa-bicycle')\n\n\n```\n\n### Trips by Duration\n\n```{r}\n\ntrips_df %>%\n    ggplot(aes(x = duration_min)) +\n    theme_bw() +\n    xlab('Trip Duration (min) \\n') +\n    ylab('# trips') +\n    geom_histogram() \n\n```\n\n\n"}
Chỉnh sửa và Chạy Mã