访问简单要素几何列以进行密度计算

Accessing Simple Feature geometry column for density calculation

我使用空间数据,并且习惯于使用 Spatial* 对象。我最近开始使用 sf 包,在某些情况下它似乎让生活更轻松。但是我在尝试使用光栅包时遇到了麻烦。在 kde2d 函数中,我需要提供每个点的 X 和 Y,这在 sp 包中很容易:

library(sp)
library(sf)
library(MASS)
library(tibble)
library(raster)

x <- tibble(a = 1:3, lon = 19:21, lat = 19:21)
coordinates(x) <- ~ lon + lat 
proj4string(x) <- "+init=epsg:4326"
density_x <- kde2d(x$lon, x$lat, n = 30, h = 1)
plot(raster(density_x))

但后来我试图使用 sf 包实现相同的目的,但发生了错误:

y <- st_as_sf(x, coords = c("lon", "lat"), crs = 4326)
density_y <- kde2d(y$lon, y$lat, n = 30, h = 1)
plot(raster(density_y))

我不知道如何像 sp 包一样进入几何列。我尝试了解决方法,但它看起来很难看:

y <- st_as_sf(x, coords = c("lon", "lat"), crs = 4326)
coords <- as.data.frame(st_coordinates(y$geometry))
density_y <- kde2d(coords$X, coords$Y, n = 30, h = 1)
plot(raster(density_y))

还有其他方法可以实现吗?也许你使用一些比 raster 更好的包来处理密度?

st_as_sf() 中将 "remove" 参数设置为 FALSE 即可:

x <- tibble(a = 1:3, lon = 19:21, lat = 19:21)
y <- st_as_sf(x, coords = c("lon", "lat"), crs = 4326, remove = F)
y

#> Simple feature collection with 3 features and 3 fields
#> geometry type:  POINT
#> dimension:      XY
#> bbox:           xmin: 19 ymin: 19 xmax: 21 ymax: 21
#> epsg (SRID):    4326
#> proj4string:    +proj=longlat +datum=WGS84 +no_defs
#> # A tibble: 3 x 4
#>       a   lon   lat         geometry
#>   <int> <int> <int> <simple_feature>
#> 1     1    19    19  <POINT (19 19)>
#> 2     2    20    20  <POINT (20 20)>
#> 3     3    21    21  <POINT (21 21)>

density_y <- kde2d(y$lon, y$lat, n = 30, h = 1)
plot(raster(density_y))