2

在 R 中沿 a 提取栅格值时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)

标志

我可以提取值并绘制它们 - 但是如何用1:length(vals)实际距离替换 x 值(下面)(例如从线左侧的 0 开始)?

vals <- extract(r, line)[[1]]
plot(1:length(vals), vals, type='o')

Rlogo_vals

我可以将单元格的提取与此处xyFromCell建议的提取单元格的坐标结合起来,但我不清楚如何走得更远。

4

2 回答 2

0

这是一个解决方案(部分基于@jvj的输入),通过尝试计算raster::extract线上提供的单元中心的正交投影,然后计算沿线的距离。

(这是一个 R 初学者脚本,可能很容易改进,但似乎有效(当然仅适用于投影距离相关的栅格))

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 !!

Rlogo_extractedValuesAlongLineWithDistance

于 2015-03-13T08:46:31.697 回答
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')
于 2015-03-07T18:23:01.967 回答