我在sf对象上的行方向操作遇到了一些问题,其中几何是多边形类型。
<_> by_row内的sf函数似乎不起作用,例如以下内容应该创建一个包含边界框对象的列表列: purrr::by_row(sf_polygons_object, function(x) {
list(st_bbox(x))
}, .to = 'bb')
UseMethod(“st_bbox”)中的错误: 没有适用于'st_bbox'的方法应用于类“c('tbl_df','data.frame')的对象”
(不是最有用的例子,但证明了问题)。
我尝试了一些替代方法,例如rowwise() %>% mutate()
,mutate( x = apply(., 1, function(x) ...))
,但没有工作,因为它们不向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')
答案 0 :(得分:5)
不需要黑客攻击。只需拆分并映射函数:
st_as_sf(ne_countries()[1:5,]) %>%
mutate(bb = split(., 1:5) %>% map(st_bbox))
答案 1 :(得分:1)
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
答案 2 :(得分:0)
我发现不使用管道要容易得多。这是皮埃尔的答案,没有管道改写:
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)