knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

Tutorials taken from The Raster package by Robert J. Hijmans

suppressPackageStartupMessages({
  # reading, writing, manipulating, analyzing and modeling of gridded spatial data
  library(raster)
  # simple features spatial vector data
  library(sf)
  # creating graphics based on Grammar of Graphics
  library(ggplot2)
})
# represent large satellite image collections as regular raster data cubes with 
# dimensions bands, time, y and x
# library(gdalcubes)
# reading, manipulating, plotting and writing spatiotemporal data array cubes
# library(stars)
rasterOptions()

Raster layer

create raster

r1 <- raster(ncol = 10, nrow = 10, xmn = 0, xmx = 1000, ymn = 0, ymx = 1000)
r1

#change resolution
res(r1) <- 200
r1

# change number of rows and columns
ncol(r1) <- 10
nrow(r1) <- 10
r1

# set coordinate reference system
projection(r1) <- "+proj=utm +zone=48 +datum=WGS84"
r1

# add cell values
values(r1) <- 1:ncell(r1)
as.matrix(r1)
r1
plot(r1, main = 'Raster with 100 cells')

freq

freq(r1)[1:5, ]

projectExtent

r <- projectExtent(r1, crs = crs(r1))
r

Explore raster cells

as.matrix(r1)

# check if raster has values
hasValues(r1)

# check if raster values stored in memory
inMemory(r1)

# dimensions
dim(r1)

# number of columns
ncol(r1)

# number of rows
nrow(r1)

# which row contains the cell number
rowFromCell(r1, 45)

# which column contains the cell number
colFromCell(r1, 45)

# what are the x and y coordinates for cell number
xyFromCell(r1, 45)

# what cell number is at coordinates x and y
cellFromXY(r1, c(450, 550))

# what column number is at coordinate x
colFromX(r1, 450)

# what row number is at coordinate y
rowFromY(r1, 550)

Raster stack

r2 <- r3 <- r1
values(r2) <- 101:200
as.matrix(r2)
values(r3) <- 201:300
as.matrix(r3)

s <- stack(r1, r2, r3)
nlayers(s)
s
plot(s)

subset

r <- subset(s, 1)
as.matrix(r)

Raster brick

b <- brick(r1, r2, r3)
# b <- brick(s)
nlayers(b)
b
plot(b)
# Extract a raster layer from a raster brick
r2 <- raster(b, layer = 2)
r2
plot(r2)

Vector to Raster layer

rasterize

Extract cell values

r <- r1[1:3, 1:3, drop = FALSE] # row number, column number
r
as.matrix(r)

extract

extract(r1, y = 12) # what cell value occurs at cell number(s)
# extract(r1, y = sf object, weights = TRUE) # polygon or line vector

getValues

# get cell values from row number
getValues(r1, 5)

getValuesBlock

as.matrix(r1)
getValuesBlock(r1, row = 4, nrows = 3, col = 4, ncols = 3)

Summarise cell values

cellStats

# apply summary function within each raster layer in a raster stack
cellStats(r1, sum)

frequency

r <- raster(ncols = 10, nrows = 10, vals = round(runif(100, 0, 1)))
freq(r)

zonal

r <- projectExtent(r1, crs = crs(r1))
values(r) <- rep(1:10, 10)
as.matrix(r)
rz <- zonal(r1, r, fun = 'max')
rz

crosstab

Modify raster values

calc

r <- r1 * 2
r <- calc(r1, fun = function(x){x * 2})
as.matrix(r)
r <- r1
f <- function(x) {
  x[x == 5] <- NA
  return(x)
}
r <- calc(r, f)
as.matrix(r)

reclassify

r <- reclassify(r1, c(1, 10, 1, 10, 20, 2, 20, 30, 3))
as.matrix(r)

subs

r <- subs(r1, data.frame(from = c(10, 20), to = c(1, 2),
                         by = 'from',
                         which = 'to',
                         subsWithNA = FALSE))
as.matrix(r)

focal

r <- raster(ncols = 20, nrows = 20, vals = round(runif(400, 0, 1) * 0.7))
as.matrix(r)
rc <- clump(r)
as.matrix(rc)
plot(rc)

update

Modify raster extent

crop

r <- crop(r1, extent(300, 700, 300, 700))
as.matrix(r)
r
plot(r1, legend = FALSE)
plot(r, add = TRUE)

extend

r <- extend(r, extent(0, 1000, 0, 1000))
as.matrix(r)
r

trim

r <- trim(r)
as.matrix(r)
r

shift

r <- shift(r, dx = 200, dy = 200)
r
plot(r1, legend = FALSE)
plot(r, add = TRUE)

Modify raster resolution

aggregate

r <- aggregate(r1, fact = 2, fun = sum)
as.matrix(r)
r
plot(r)

disaggregate

r <- disaggregate(r, fact = 2)
as.matrix(r)
r
plot(r)

Modify raster projection

projectRaster

Modify between raster layers

mask

# remove numbers divisible by 10
## create masking raster with TRUE / FALSE values
masking_raster <- r1 %% 10
masking_raster <- masking_raster == 0
as.matrix(masking_raster)

## use masking raster to remove numbers divisible by 10
r <- r1
r[masking_raster] <- NA
as.matrix(r)

# mask removes all values in r2 that are NA in r
rm <- mask(r2, r)
as.matrix(rm)

cover

as.matrix(rm)
rm <- cover(rm, r1)
as.matrix(rm)

overlay

st <- overlay(r1, r2, r3, fun = mean)

# can also use summary functions directly
st <- mean(r1, r2, r3) # across raster layers
st <- mean(s) # layers within raster stack
as.matrix(st)

merge

rl <- crop(r1, extent(0, 600, 0, 1000))
rr <- crop(r2, extent(400, 1000, 0, 1000))
r <- merge(rl, rr)
as.matrix(r)
r
plot(r)

resample

r <- projectExtent(r1, crs = crs(r1))
r <- resample(r1, r, method = 'bilinear')
as.matrix(r)
r
plot(r)

Identify value patterns

clump

r <- raster(ncols = 12, nrows = 12, vals = round(runif(144, 0, 1) * 0.7))
as.matrix(r)
rc <- clump(r)
as.matrix(rc)
plot(rc)

boundaries

Identify value distances

distance

pointDistance

gridDistance

adjacent

direction

Raster to Vector layer

rasterToPoints

pt <- rasterToPoints(r1, spatial = TRUE)
pt <- st_as_sf(pt)
ggplot(pt, aes(color = layer)) +
  geom_sf() +
  scale_color_viridis_c()

rasterToPolygons

py <- rasterToPolygons(r1)
py <- st_as_sf(py)
ggplot(py, aes(fill = layer)) +
  geom_sf() +
  scale_fill_viridis_c()

Large raster files

Processing data in chunks

Multi-core functions



gcfrench/store documentation built on May 17, 2024, 5:52 p.m.