This tutorial is to help R beginners to have an idea of using R for spatial analysis.It assumes that beginners have no prior knowledge of R, but some experience should help. You will experience using R for loading data, visualizing both vector and raster data and manipulating those data. You will learn a great details of R for spatial mapping as we progress.
R is a programming language, where people have developed many packages to make our life easier. So We will make use of those packages to benefit our work
Everytime, you want to use a R package, you have to load it in R environmet by writing library(package_name)
library(ggplot2)
library(ggmap)
## Warning: package 'ggmap' was built under R version 3.4.2
library(rgeos)
## Warning: package 'rgeos' was built under R version 3.4.2
## rgeos version: 0.3-25, (SVN revision 555)
## GEOS runtime version: 3.6.1-CAPI-1.10.1 r0
## Linking to sp version: 1.2-5
## Polygon checking: TRUE
library(maptools)
## Loading required package: sp
## Checking rgeos availability: TRUE
library(tmap)
## Warning: package 'tmap' was built under R version 3.4.2
library(tidyverse)
## Loading tidyverse: tibble
## Loading tidyverse: tidyr
## Loading tidyverse: readr
## Loading tidyverse: purrr
## Loading tidyverse: dplyr
## Conflicts with tidy packages ----------------------------------------------
## filter(): dplyr, stats
## lag(): dplyr, stats
x=1:500
y=sin(x/10)*exp(x*-0.0001)
plot(x,y,col=rainbow(100))
Read spatial data shp file in R
library(raster)
##
## Attaching package: 'raster'
## The following object is masked from 'package:dplyr':
##
## select
## The following object is masked from 'package:tidyr':
##
## extract
# Reading VN map
VN<-getData("GADM",country="Vietnam",level=1)
HN<-VN[VN@data$VARNAME_1=="Ha Noi City|Hanoi",]
plot(HN)
# Extracting VN at level 3
VN3<-getData("GADM",country="Vietnam",level=3)
## Clipping Hanoi communes from HN (Hanoi boundary)
HN3<-crop(VN3,HN)
plot(HN3,col=rainbow(100),axes=T,main="Ha Noi Map")
Creating a new random variable
set.seed(123)
HN3$Distribution<-rnorm(nrow(HN3),10,9) # Create a variable named `Distribution`
myclass<-c("A","B","C","D","F")
HN3$Class1<-sample(myclass,nrow(HN3),replace = T) # Creating a new randonly categorical variable
head(HN3@data)
plot(HN3,axes=T,col=2, main="Distribution>20/Blue")
HN4<-HN3[HN3$Distribution>20,]
plot(HN4,col=4,axes=T,add=T)
Removing and reprojecting coordinate system
library(sp)
proj4string(HN3)<-NA_character_ # Remove coordinate system
proj4string(HN3)<-CRS("+proj=utm +zone=48 +data=WGS84") # reprojecting a new coordinate system utm
plot(HN3,col=3,axes=T,main="Hanoi Map")
Using tmap package to visualize map
library(tmap)
qtm(HN3,"Class1") # Using a categorical variable
qtm(HN3,"Distribution")
qtm(shp = HN3, fill = c("Distribution", "ID_3"), fill.palette = "Blues", ncol = 2)