1

我正在尝试使用terra::distance我会使用raster::distanceFromPoints的 . 但是,terra::distance仅报告从点到 NA 单元的距离。这是预期的结果吗?我在我的解决方法中包含了示例代码。

带点的栅格图用于距离计算

使用对角线 NA 单元格绘制或栅格并指向 50,50

terra::distance 的点图

terra::distance 栅格显示仅针对 NA 像元计算的距离

期望的输出

使用 terra::distance 获取距离值的解决方法

r <- terra::rast(ncols=10, nrows=10)
valR <- rep(1, length = 100)
valR[c(1,12,23,34,45,56,67,78,89,100)] <- NA
terra::values(r) <- valR

xp <- c(50)
yp <- c(50)
xyp <- cbind(xp, yp)
vecP <- terra::vect(xyp)

terra::plot(r)
terra::plot(vecP, add=T)

rDist <- terra::distance(r, vecP)
terra::plot(rDist) #only NA cells have the distance value

# WORKAROUND
r1 = r*0
r1[is.na(r1)] <- 100
r1[r1<1] <- NA
r1Dist <- terra::distance(r1, vecP)
terra::plot(r1Dist)

####################
# using raster::distanceFromPoints
####################

rR <- raster::raster(ncols=10, nrows=10)
raster::values(rR) <- valR
raster::plot(rR)

rRDist <- raster::distanceFromPoints(rR, xyp)
rRDist <- raster::mask(rRDist, rR)
raster::plot(rRDist)
4

1 回答 1

2

I tested this using distance to a SpatVector of lines rather than points. That seems to work as expected. I assume that maybe it has not been implemented for points yet.

So, another workaround you could use is to calculate distance to lines of zero length (which are basically equivalent to points):

x1 <- rbind(c(50,50), c(50,50))
colnames(x1) <- c('x', 'y')
lns <- vect(x1, "lines")

rDist <- distance(r, lns)
plot(rDist) 

enter image description here

于 2021-12-08T18:50:23.540 回答