Lecturers’ presentation

Paul Daigle

Ghizlene Zerguini

Ikram Mecheri

Why use maps?

Dataset

Primer

Libraries

To call a library (a.k.a. packages) in R, use library(libraryName).

Useful packages (ones used for this workshop in bold) :

  • dplyr
  • ggplot2
  • shiny
  • lubridate
  • leaflet and leaflet.extra
  • gbfs
  • rjson
library(gbfs)
library(dplyr)
library(rjson)
library(leaflet)
library(leaflet.extras)

Data import (csv, rds)

# Importing the trips data from a csv file
df <- read.csv("data/OD_2018-07.csv")

# Importing the stations location using a RDS file
stations <- readRDS("data/mtlBixiStations.rds")

Data import (RSS feed)

# Import the json file containing the urls to access the RSS feed
jsonFile <- fromJSON(file = "gbfs.json")

# Access the RSS feed using the gbfs library (function automatilly saves a RDS file)
get_station_information(jsonFile$data$fr$feeds[[2]]$url, directory = "data", file= "mtlBixiStations.rds")

Data manipulation (merge)

# Using the table function on the start_station_code variable, we are able to compute the number of occurences of departures at each station
res <- data.frame(table(df$start_station_code))

# We want to rename the columns (not mandatory)
colnames(res) <- c("station_code", "Freq")

# We filter on a certain condition
res <- filter(res, Freq > 100)

# We merge two tables together on different key names. The argument all.x = T is equivalent to doing a left join
merged.res <- merge(res, stations[,c("short_name", "lat", "lon")], 
                   by.x = "station_code", 
                   by.y = "short_name",
                   all.x = T)

Data export (csv)

# Output the dataframe as a csv file
write.csv(merged.res, "trips_GPS.csv")

Maps

# Import
carAccidents <- read.csv("data/carAccidents.csv")

# Convert to date format
carAccidents$DT_ACCDN <- as.Date(carAccidents$DT_ACCDN)

# Filter to get data before 2013
carAccidents <- filter(carAccidents, DT_ACCDN < as.Date("2013-01-01"))

# Adding a Frequancy column
carAccidents$Freq <- 1

# Creating a map: 1. Create a leaflet object 2. Add a background/map (Tiles) 3. Add markers/point, with a the cluster option
m <- leaflet(carAccidents) %>% addTiles() %>% addMarkers(lng=~LOC_LONG, lat=~LOC_LAT, clusterOptions = markerClusterOptions())

# Call the leaflet object to output it
m

Heatmaps

# Creating a map: 1. Create a leaflet object 2. Add a background/map (Tiles) 3. Add heatmap "markers"
m <- leaflet(na.omit(merged.res)) %>% addTiles() %>% addWebGLHeatmap(lng=~lon, lat=~lat, intensity=~Freq/10000, size= 500)

# Call the leaflet object to output it
m