Where have I been?


I began this blog in the summer of 2018, mostly because I needed a place to put all of the things I do for fun. What better way than to build your own website and put all that stuff there? I have come across this beautiful post from the D3js website. It creates a plot of where the author has been. I will recreate the same plot here, but with the leaflet package in R.

We will load in the data for the cities and states that I’ve lived.

require(leaflet) #packages
## Loading required package: leaflet
require(DT)
## Loading required package: DT
require(rgdal)
## Loading required package: rgdal
## Loading required package: sp
## rgdal: version: 1.2-16, (SVN revision 701)
##  Geospatial Data Abstraction Library extensions to R successfully loaded
##  Loaded GDAL runtime: GDAL 2.1.2, released 2016/10/24
##  Path to GDAL shared files: /Library/Frameworks/R.framework/Versions/3.3/Resources/library/rgdal/gdal
##  GDAL binary built with GEOS: FALSE 
##  Loaded PROJ.4 runtime: Rel. 4.9.1, 04 March 2015, [PJ_VERSION: 491]
##  Path to PROJ.4 shared files: /Library/Frameworks/R.framework/Versions/3.3/Resources/library/rgdal/proj
##  Linking to sp version: 1.2-5
cities <- read.csv(url, header = T)
DT::datatable(cities)

Leaflet comes with an easy to use pipeline: %>%. For example, given two functions as.character() and as.numeric(), we could code this two different ways.

x <- factor(c("12.99", "99.01", "20"))

#Method one:
as.numeric( as.character(x) )
## [1] 12.99 99.01 20.00
#Method two:

x %>% as.character %>% as.numeric
## [1] 12.99 99.01 20.00
#But incorrect output of factor to numeric
as.numeric(x)
## [1] 1 3 2

This is important to note because we will utilize the pipe notation.

We have already loaded leaflet and the datasets, we just need to use them!

We will first load the leaflet base plot and add tiles:

L <- leaflet(data = cities) %>% 
  addTiles()
L

When we add out points, the mapview is automatically updated as well!

L %>%
  addCircles(lat = ~lat, lng = ~lon, radius = ~years*1000 , stroke = F, fillOpacity = .5)

Back to blog

In God we trust. All others must bring data.

- W. Edwards Deming, Statistician