Guide to Creating Interactive Maps in R
Chapter 1 Prerequisites
1.1 Watch the precursor videos
Prior to working through the exercises and modules in this book, please watch the precursor videos that provide an introduction to GIS and geospatial data. The videos can be found here:
1.2 Download R and RStudio
First things first, you should install the R and RStudio softwares. To download R, visit the webpage https://cloud.r-project.org. You should see three download links at the top of the page, please click and install the appropriate R software for your machine (Linux, Mac OS, or Windows). Next, install RStudio Desktop from the webpage https://rstudio.com/download. RStudio is an IDE, integrated development environment, and it allows us to write R code in a user-friendly manner. RStudio itself will not work without R already installed.
When you open RStudio to begin writing R code, you will notice that the display appears as such:
To start writing R code, click on the button on the top left corner, above the R Console. Alternatively, you can click on File > New File > R Script to create an empty R Script.
1.3 Installing libraries
For making maps, we will be using several packages, otherwise known as libraries. These packages have different functions that serve different purposes. To use the functions, data, and documentation within a package, you must first install that package and then import that package. Here, we import the leaflet
package to create interactive maps, while the other rgdal
and raster
packages are to analyze geospatial data. You can install these packages using the code:
install.packages("leaflet")
install.packages("rgdal")
install.packages("raster")
Once you install these packages, you won't need to reinstall them so you can delete those lines of code. On the contrary though, whenever you create an R script, you will need to import those packages each time. To import a package, use the library()
function.
library(leaflet) #for making the interactive map
library(rgdal) #for importing vector data
library(raster) #for importing raster data
Note: You always need to put quotation marks around the package name when you are installing an R package (e.g. install.packages("package name")
); however, you do not need to put quotation marks when you are importing the package into your R session (e.g. library(package name)
).