Reputation: 149
I have the following raster
library(raster)
r <- raster(ncol=2421, nrow=5005)
r:
class : RasterLayer
dimensions : 2421, 5005, 12117105 (nrow, ncol, ncell)
resolution : 1, 1 (x, y)
extent : 501121, 506126, 2809088, 2811509 (xmin, xmax, ymin,
ymax)
crs : +proj=utm +zone=17 +datum=WGS84 +units=m +no_defs
+ellps=WGS84 +towgs84=0,0,0
source : E:/Datat Layers/Clip/Harney_XMerge.tif
names : Harney_XMerge
values : -3.126388e-13, 57.14 (min, max)
and the following transect in the form of polylines
Line:
class : SpatialLinesDataFrame
features : 7
extent : 500864.6, 505506.2, 2809553, 2811079 (xmin, xmax, ymin,
ymax)
crs : +proj=utm +zone=17 +datum=WGS84 +units=m +no_defs
+ellps=WGS84 +towgs84=0,0,0
variables : 3
names : OBJECTID, Id, Shape_Leng
min values : 1, 0, 2716.24783826
max values : 7, 0, 3188.64130203
I want to extract the coordinates of each pixel that falls along the transect but haven't been able to find any function that does so on my own.
I have used the following extract function but it only extracts the info from the raster in this case tree height data. Is there a way for me to use the extract function or another function to extract the UTM coordinates of each pixel that fall along my established transects?
extract(r,line )
Upvotes: 0
Views: 205
Reputation: 47146
Here is a minimal reproducible example (copied from, ?raster::extract
):
library(raster)
r <- raster(ncol=36, nrow=18, vals=1)
cds1 <- rbind(c(-50,0), c(0,60), c(40,5), c(15,-45), c(-10,-25))
cds2 <- rbind(c(80,20), c(140,60), c(160,0), c(140,-55))
lines <- spLines(cds1, cds2)
extract(r, lines)
In the documentation of extract (?extract
) you can see that there is an argument cellnumbers
. You can do
e <- extract(r, lines, cellnumbers = TRUE)
That returns a list with, for each polyline, a matrix with cellnumbers and values. From the cellnumbers you can get the coordinates.
f <- lapply(e, function(x) xyFromCell(r, x[,1]))
Or if you prefer a data.frame
e <- extract(r, lines, cellnumbers = TRUE, df=T)
d <- data.frame(ID=e[,1], xyFromCell(r, e[,2]))
head(d)
# ID x y
#[1,] 1 -5 55
#[2,] 1 5 55
#[3,] 1 -15 45
#[4,] 1 -5 45
#[5,] 1 5 45
#[6,] 1 15 45
If you want need the points to be ordered along the line, use the extract argument along=TRUE
Upvotes: 1