I've combed through R's raster functions and vignettes and can't seem to get this working.
I want to specify a line/vector across a raster stack (a DEM and possibly related variables), and get a profile of values for the cells which the line intersects. I've been able to do something similar using mask
with a polygon.
EDIT: Thanks to scw, I have developed the following solution.
# I have a stack of environmental rasters in this format
new_r <- raster(ncol=615, nrow=626, xmn=-156.2, xmx=-154.8, ymn=18.89, ymx=20.30)
res(new_r) <- 0.00225
projection(new_r) <- "+proj=longlat +ellps=GRS80 +datum=NAD83 +no_defs +towgs84=0,0,0"
values(new_r) <- outer(seq_len(nrow(new_r)), seq_len(ncol(new_r)), "+")
stackdata <- stack(new_r, sqrt(new_r))
# I designate two transect lines by long/lat
cds1 <- rbind(c(-156, 19), c(-155.5, 20.2))
cds2 <- rbind(c(-155, 20.2), c(-155, 19.2))
transects <- SpatialLines(list(Lines(list(Line(cds1)), ID = "one"),
Lines(list(Line(cds2)), ID = "two")))
# plot the lines to confirm placement
plot(new_r)
plot(transects, add = TRUE)
# and return a list whose length is equal to the number of line segments,
# and each list element is a matrix with a column for each raster layer
e <- extract(stackdata, transects)
extract
function prints an annoying long string of1
s while it runs. This can be hidden withinvisible(capture.output(e <- extract(...)))
, but is there an easier way?