如何在R中识别与线相交的栅格单元?

3

问题

我有一些空间线(作为 terra::vect() 对象),我想将它们与栅格(terra::rast())相交,以便识别每条线相交的单元格 id。

输出应该是一个长格式的 data.frame,包含列 line_idcell_id(见下面的示例)。

可能的解决方案

我更喜欢使用 terra 解决方案,但我也可以接受使用 sfstarsraster 等包的解决方案。

对栅格进行矢量化是一种选择,但是我的真实数据非常大 - 我可能很容易遇到性能问题。因此,我希望不使用栅格矢量化就能完成。

我考虑过使用 terra::intersect(),但它不接受 SpatRasters 作为参数。而 terra::rasterizeGeom() 不返回 ids,而是计算长度等信息。

示例

library("terra")

# Create example lines
v <- vect(system.file("ex/lux.shp", package="terra"))
lns <- as.lines(v)[c(1,7), "ID_1"] # filter for two lines only & only keep ID
names(lns) <- "line_id"
lns
# class       : SpatVector 
# geometry    : lines 
# dimensions  : 2, 1  (geometries, attributes)
# extent      : 5.826232, 6.381701, 49.46498, 50.18162  (xmin, xmax, ymin, ymax)
# coord. ref. : lon/lat WGS 84 (EPSG:4326) 
# names       : line_id
# type        :   <num>
# values      :       1
#                     2

# Create example raster
r <- rast(v, res=.26)
r <- init(r, fun=1:ncell(r))
names(r) <- "cell_id"
r
# class       : SpatRaster 
# dimensions  : 3, 3, 1  (nrow, ncol, nlyr)
# resolution  : 0.26, 0.26  (x, y)
# extent      : 5.74414, 6.52414, 49.44781, 50.22781  (xmin, xmax, ymin, ymax)
# coord. ref. : lon/lat WGS 84 (EPSG:4326) 
# source      : memory 
# name        : cell_id 
# min value   :       1 
# max value   :       9 

# Plot example
plot(r)
text(r) # add cell_ids as labels to plot
plot(lns, add = T)

示例

对于这个示例,我希望我的输出data.frame看起来像这样:

# data.frame(line_id = c(1,1,1,2,2),
#             cell_id = c(1,2,5,8,9))
#
#     line_id cell_id
# 1       1       1
# 2       1       2
# 3       1       5
# 4       2       8
# 5       2       9
1个回答

6

我只是使用 terra::extract(),有什么东西我没注意到吗?

extract(r, lns)
#>   ID cell_id
#> 1  1       1
#> 2  1       2
#> 3  1       5
#> 4  2       8
#> 5  2       9

这正是我所需要的。我不知怎地忽略了 terra::extract,或者没有将抽取与交集联系起来。 - chamaoskurumi
2
intersect 创建一个新的空间对象,位于输入对象之间(在这里并不适用)。extract 返回交集处第二个对象的属性。 - Robert Hijmans

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接