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

时间:2017-11-03 18:19:00

标签: r sf

我使用空间数据,我习惯使用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更好的包来处理密度?

1 个答案:

答案 0 :(得分:0)

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))