使用显式二元谓词子集 sfc 对象时出错

问题描述 投票:0回答:1

我不明白为什么以下代码块中的最后两个示例失败了

library(sf)
#> Linking to GEOS 3.11.2, GDAL 3.7.2, PROJ 9.3.0; sf_use_s2() is TRUE

p1 <- st_sfc(st_point(c(0, 0)))
p2 <- st_sfc(st_point(c(1, 1)))

p1[p2]
#> Geometry set for 0 features 
#> Bounding box:  xmin: NA ymin: NA xmax: NA ymax: NA
#> CRS:           NA
p1[p2, op = st_intersects]
#> Error in `[.default`(p1, p2, op = st_intersects): incorrect number of dimensions
p1[p2, , op = st_intersects]
#> Error in `[.default`(p1, p2, , op = st_intersects): incorrect number of dimensions

[.sfc
指定的默认操作恰好是
st_intersects
时。

sf:::`[.sfc`
#> function (x, i, j, ..., op = st_intersects) 
#> {
#>     if (!missing(i) && (inherits(i, "sf") || inherits(i, "sfc") || 
#>         inherits(i, "sfg"))) 
#>         i = lengths(op(x, i, ...)) != 0
#>     st_sfc(NextMethod(), crs = st_crs(x), precision = st_precision(x), 
#>         dim = if (length(x)) 
#>             class(x[[1]])[1]
#>         else "XY")
#> }
#> <bytecode: 0x00000255ad682df8>
#> <environment: namespace:sf>

创建于 2024-01-21,使用 reprex v2.0.2

你能帮我一下吗?在子集

op
对象时,如何正确指定
sfc
参数?

r r-sf
1个回答
0
投票

出现这里的问题是因为

`[.sfc`
在内部使用了
NextMethod()
。其工作方式是将您显式传递给
`[.sfc`
的参数传递给列表的默认子集方法。这是原始
"["
函数,在 C 代码函数
do_subset_dflt
中实现。

对于 R 函数来说,不同寻常的是,这会忽略任何参数的名称(

drop
除外),并且仅按顺序进行:

my_list <- list(a = 1, b = 2)

my_list[the_name_of_this_argument_is_ignored = 2]
#> $b
#> [1] 2

my_list[the_name_of_this_argument_is_ignored = 2, drop = FALSE]
#> $b
#> [1] 2

这甚至会导致令人困惑的结果

my_mat <- matrix(1:4, 2, 2)

my_mat[i = 1, j = 2]
#> [1] 3

my_mat[j = 1, i = 2]
#> [1] 3

在这种情况下,如果(非丢弃)参数的数量超过了对象的维数,我们就会得到你的错误:

my_list[2, op = sf::st_intersects]
#> Error in my_list[2, op = sf::st_intersects] : 
#>   incorrect number of dimensions

没有任何直接的解决方法,因为

[
是一个原始函数。使用
NextMethod
意味着命名参数
op
实际上不可供最终用户使用。既然文件表明是这样,那么我会认为这是一个错误。同时,最好的办法是避免使用
op
参数,而直接使用谓词函数:

library(sf)
#> Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE

p1 <- st_sfc(st_point(c(0, 0)))
p2 <- st_sfc(st_point(c(1, 1)))

p1[lengths(st_intersects(p1, p2)) != 0]
#> Geometry set for 0 features 
#> Bounding box:  xmin: NA ymin: NA xmax: NA ymax: NA
#> CRS:           NA

创建于 2024-01-21,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.