R 包栅格和 sp 中的函数是否保留像元编号顺序?



我正在使用 R 包中的函数rastersp来计算各种大小圆圈中所有像素的汇总统计信息。为了在处理许多栅格时节省时间,我使用xyFromCell()spDistsN1()函数预先计算了栅格中每个点与中心点的距离。该函数返回长度等于栅格中像元数的矢量。此外,我还使用as.data.frame()函数将栅格转换为行数等于栅格中像元数的数据框。然后,我可以通过查找距离小于或等于圆圈大小的所有行来索引数据框,并计算汇总统计信息。我只是想检查这两个函数是否保留了单元格编号顺序。请参阅下面的示例代码。它似乎有效,但我希望有人确认这一点。

library(raster)
# Make fake raster
foo <- matrix(1:100, nrow=10)
rfoo <- raster(foo)
# Get coordinates of each cell
cfoo <- xyFromCell(rfoo, 1:ncell(rfoo))
# Distances from center point to the coordinate of each cell
distfoo <- spDistsN1(cfoo, c(0.5, 0.5))
# Radius of circle to extract
r <- 0.25
# Coerce raster to data frame
dffoo <- as.data.frame(rfoo)
# If correct, these values should be the cell values for all cells within 0.25 of the center point
dffoo[distfoo <= r, 1]

我相信你的代码运行良好。我重复了您的工作,但使用不同的软件包,sf,进行相同的分析。我们得到了相同的结果。

library(raster)
library(sf)
    
# Make fake raster
foo <- matrix(1:100, nrow=10)
rfoo <- raster(foo)
# Convert raster to a matrix with point information
rfoo_m <- rasterToPoints(rfoo)
# Convert to a data frame
rfoo_df <- as.data.frame(rfoo_m)
# Convert to sp object
rfoo_sf <- st_as_sf(rfoo_df, coords = c("x", "y"))
# Create a sp object as one point with coordinate 0.5, 0.5
target_sf <- st_point(c(0.5, 0.5))
# Calculate the distance, store the reuslt as a new column in rfoo_df
rfoo_df$dist <- st_distance(rfoo_sf, target_sf)
# Filter rfoo_df with dist <- 0.25
rfoo_df[rfoo_df$dist <= 0.25, "layer"]
[1] 34 44 54 64 35 45 55 65 36 46 56 66 37 47 57 67

标杆

在这里,我比较了OP的spDistsN1方法和我帖子中st_distance方法之间的性能。

library(microbenchmark)
microbenchmark(
m1 = {dist_col <- st_distance(rfoo_sf, target_sf)},
m2 = {distfoo <- spDistsN1(cfoo, c(0.5, 0.5))}
)
Unit: microseconds
expr     min      lq       mean   median      uq      max neval
m1 933.356 941.695 1011.94994 948.4305 982.429 1903.275   100
m2  13.471  16.679   24.40241  25.6590  28.867   69.922   100

似乎spDistsN1要快得多。

最新更新