在R中沿SpatialLine
提取栅格的值时,如何将这些值与沿此线的实际距离联系起来?
假设我想沿着以下行提取R徽标的值:
library(raster)
r <- raster(system.file("external/rlogo.grd", package="raster"))
x=c(5, 95)
y=c(20, 50)
line = SpatialLines(list(Lines(Line(cbind(x,y)), ID="a")))
plot(r)
plot(line, add=TRUE)
我可以提取值并绘制它们 - 但是如何用实际距离替换x值(下面的1:length(vals)
)(从例如线的左侧开始,例如0)?
vals <- extract(r, line)[[1]]
plot(1:length(vals), vals, type='o')
我可以将细胞提取与xyFromCell
结合起来,按照建议here获取提取细胞的坐标,但我不清楚如何更进一步。
答案 0 :(得分:0)
我不确定你要问的是什么,但是如果你想寻找线段最左边坐标和线穿过的单元中心之间的距离,那么你可以找到像这样的距离:
x <- extract(r, l, cellnumbers=TRUE)[[1]]
xy <- xyFromCell(r, x[,1]) # get cell coordinates where the line passes
start <- xy[which.min(xy[,1]),] # leftmost coordinate of the line
d <- apply(xy, 1, function(x, start) sqrt(sum((x-start)^2)), start=start) # find distances between the line segment start and the cells
plot(1:length(d), d, type='o')
答案 1 :(得分:0)
这是一个解决方案(部分基于@jvj的输入),试图计算线上raster::extract
提供的单元中心的正交投影,然后计算沿着该线的距离线。
(这是一个R-beginners脚本,可能很容易改进,但似乎有用(当然只适用于有距离投影的栅格))
vals <- extract(r, line, cellnumbers=TRUE)[[1]]
cellsxy <- xyFromCell(r, vals[,1]) # coordinates of intersected cells (likely not ON the line)
linexy = spsample(line, 1000, "regular") # get the line as points
linexy <- matrix(cbind(linexy$x, linexy$y), ncol=2) # easier than Spatial object for later
orthoproj <- c() # to store the orthogonal projections of cells centres on the line
for (i in 1:nrow(cellsxy)) {
xypt = cellsxy[i,]
min.index <- which.min(spDistsN1(linexy, xypt))
orthopt <- linexy[min.index, ] # orthogonal projections = smaller distance
orthoproj <- c(orthoproj, c(orthopt[1], orthopt[2]))
}
orthoproj <- matrix(orthoproj, ncol=2, byrow=T)
orthoproj <- data.frame(x=orthoproj[,1], y=orthoproj[,2])
orthoproj <- orthoproj[order(orthoproj[,1]),] # reorder with increasing distance
orthoproj <- data.frame(x=orthoproj$x, y=orthoproj$y)
start <- linexy[which.min(linexy[,1]),] # leftmost coordinate of the line
dists <- apply(orthoproj, 1,
function(xy, start) sqrt(sum((xy-start)^2)),
start=start) # distances between 'start' and the orthogonal projections
plot(dists, rev(vals[,2]), type='o') # !! beware: order of 'vals' and 'dists'
# depending on the order in which cellnumbers are returned
# in raster::extract and the shape of your line !!