This project uses data from the NY Citi Bike site that can be obtained here: https://s3.amazonaws.com/tripdata/index.html. The dataset for this leaflet project is from 201609-citibike-tripdata.zip.
# Load the libraries needed for the project
library(leaflet)
## Warning: package 'leaflet' was built under R version 3.2.5
library(plyr)
# Read the data downloaded from the link above
df <- read.csv("C:/Users/karlk/Desktop/201609-citibike-tripdata/201609-citibike-tripdata.csv", header = TRUE)
# Extract the start station id, latitude, and longitude
dfStart <- df[ ,c("start.station.id", "start.station.latitude", "start.station.longitude")]
# Extract the end station id, latitude, and longitude
dfEnd <- df[ ,c("end.station.id", "end.station.latitude", "end.station.longitude")]
# Create column names that can be used by both end and start data so they can be r binded
names <- c("stationID", "stationLat", "stationLon")
colnames(dfStart) <- names
colnames(dfEnd) <- names
TotalStations <- rbind(dfStart, dfEnd)
# Count the number of rides that either started or ended at a given station
CountStation <- ddply(TotalStations, .(stationID), summarize, freq=length(stationID))
# subset to unique stations
UniqueStations <- unique(TotalStations)
# Set the inital view of leaflet to be at the median station location
initial_lat = median(UniqueStations$stationLat)
initial_lng = median(UniqueStations$stationLon)
initial_zoom = 12
PlotDF <- merge(UniqueStations, CountStation, by = "stationID")
Plot the data set created above, the popup shows the station ID and the number of visits.
leaflet(PlotDF) %>% addTiles() %>%
setView(lat = initial_lat, lng = initial_lng, zoom = initial_zoom) %>%
addCircles(lng = ~stationLon, lat = ~stationLat, weight = 1,
radius = ~ sqrt(freq), popup = ~paste("StationID: ", as.character(stationID), ", Total Visits: ", freq, sep = "")
)