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