Learn R Programming

inlmisc (version 0.2.4)

ExtractAlongTransect: Extract Raster Values Along Transect Line

Description

This function extracts values from raster layer(s) along a user defined transect line.

Usage

ExtractAlongTransect(transect, r)

Arguments

transect
SpatialPoints or SpatialLines. Transect line or its vertices.
r
RasterLayer, RasterStack, or RasterBrick. Raster layer(s)

Value

A list is returned with components of class SpatialPointsDataFrame. These components represent continuous piecewise line segments along the transect. The following variables are specified for each coordinate point in the line segment:
dist
distance along the transect line.
2, …, n
extracted value for each raster layer in r, where column names match their respective raster layer name.

Details

The transect line is described using a simple polygonal chain. The transect line and raster layer(s) must be specified in a coordinate reference system.

See Also

PlotCrossSection

Examples

Run this code
library(raster)

coords <- rbind(c(-100, -90), c(80, 90), c(80, 0), c(40, -40))
crs <- CRS("+init=epsg:4326")
transect <- SpatialPoints(coords, proj4string = crs)
r <- raster(nrows = 10, ncols = 10, ymn = -80, ymx = 80, crs = crs)
names(r) <- "value"
set.seed(0)
r[] <- runif(ncell(r))
r[4, 6] <- NA
plot(r, xlab = "x", ylab = "y")
lines(SpatialLines(list(Lines(list(Line(coords)), ID = "Transect")), proj4string = crs))
points(transect, pch = 21, bg = "red")
segs <- ExtractAlongTransect(transect, r)
for (i in 1:length(segs)) points(segs[[i]], col = "blue")

dev.new()
xlab <- "Distance along transect"
ylab <- "Raster value"
xlim <- range(vapply(segs, function(seg) range(seg@data[, "dist"]), c(0, 0)))
ylim <- range(vapply(segs, function(seg) range(seg@data[, "value"], na.rm = TRUE),
                     c(0, 0)))
plot(NA, type = "n", xlab = xlab, ylab = ylab, xlim = xlim, ylim = ylim)
for (i in 1:length(segs))
  lines(segs[[i]]@data[, c("dist", "value")], col = rainbow(length(segs))[i])
coords <- coordinates(transect)
n <- length(transect)
d <- cumsum(c(0, as.matrix(dist((coords)))[cbind(1:(n - 1), 2:n)]))
abline(v = d, col = "grey", lty = 2)
mtext(paste0("(", paste(head(coords, 1), collapse = ", "), ")"), adj = 0)
mtext(paste0("(", paste(tail(coords, 1), collapse = ", "), ")"), adj = 1)

Run the code above in your browser using DataLab