0

我使用空间数据,并且习惯于使用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))

我不知道如何以与 package.json 相同的方式进入几何列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处理密度更好的软件包?

4

1 回答 1

1

将“remove”参数设置为 FALSEst_as_sf()就可以了:

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

于 2017-11-04T17:16:37.427 回答