对 sf 对象的行操作

row-wise operations on sf objects

我在对 sf 对象进行行向操作时遇到了一些问题,其中的几何图形是多边形类型。

by_row 中的 sf 函数似乎不起作用,例如以下应创建一个包含边界框对象的列表列:

 purrr::by_row(sf_polygons_object, function(x) {
   list(st_bbox(x))
 }, .to = 'bb')

Error in UseMethod("st_bbox") : no applicable method for 'st_bbox' applied to an object of class "c('tbl_df', 'data.frame')"

(本身不是最有用的示例,但可以说明问题)。

我尝试了一些替代方法,例如rowwise() %>% mutate()mutate( x = apply(., 1, function(x) ...)) 和 none 工作,因为它们不提供 st_bbox() 它需要的 sf 对象。这是一个错误,还是我没有很好地解决这个问题?

编辑: 可重现示例

library(sp)
library(rgdal)
library(rgeos)
library(sf)
library(tidyverse)
library(rnaturalearth)

nec <- st_as_sf(ne_countries()[1:5,]) %>%
  purrr::by_row(., function(x) st_bbox(x), .to = 'bb')

我不得不 fiddle 一点。您必须使用 sf 对象吗?在这种情况下,这将为您提供每个多边形的边界框列表:

library(sp)
library(rgdal)
library(sf)
library(tidyverse)
library(rnaturalearth)
library(rgeos)
library(purrr)

nec <- as.list(st_as_sf(ne_countries()[1:5,])$geometry) %>% lapply(., st_bbox)
nec

导致:

[[1]]
    xmin     ymin     xmax     ymax 
60.52843 29.31857 75.15803 38.48628 

[[2]]
      xmin       ymin       xmax       ymax 
 11.640096 -17.930636  24.079905  -4.438023 

[[3]]
    xmin     ymin     xmax     ymax 
19.30449 39.62500 21.02004 42.68825 

[[4]]
    xmin     ymin     xmax     ymax 
51.57952 22.49695 56.39685 26.05546 

[[5]]
     xmin      ymin      xmax      ymax 
-73.41544 -55.25000 -53.62835 -21.83231 

无需破解。只需拆分并映射功能:

st_as_sf(ne_countries()[1:5,]) %>% 
  mutate(bb = split(., 1:5) %>% purrr::map(st_bbox))

我发现不使用管道要容易得多。这是皮埃尔在没有管道的情况下重写的答案:

nec       <- st_as_sf(ne_countries()[1:5,])
nec_split <- split(nec, 1:5)
nec_map   <- map(nec_split, st_bbox)
nec       <- mutate(nec, bb = nec_map)