gpt4 book ai didi

r - 比较简单特征 {sf} 和空间对象 {sp} : speed and memory

转载 作者:行者123 更新时间:2023-12-04 15:30:00 25 4
gpt4 key购买 nike

我在 R 中使用了一些空间数据,想知道是使用依赖于旧空间格式(包 sp)的包/函数还是新包 sf。我做了这个测试,基于找到的代码 here .

这个想法是“识别关于空间点数据集中每个点的最大距离 xx 米内的所有点”。

library(tictoc)

# define a buffer distance and a toy data
maxdist <- 500
df<-data.frame(x = runif(10000, 0, 100000),y = runif(10000, 0, 100000),id = 1:10000)

# doing the analysis using sf
library(sf)
tic("sf")
pts <- df %>% st_as_sf(coords = c("x", "y"))
pts_buf <- st_buffer(pts, maxdist,nQuadSegs = 5)
int <- st_intersects(pts_buf, pts)
toc()

# doing the analysis using sp
library(sp)
library(rgeos)
tic("sp")
pts2 <- SpatialPointsDataFrame(df[,1:2],as.data.frame(df[,3]))
pts_buf2 <- gBuffer(pts2, byid=TRUE,width=maxdist)
int2 <- over(pts_buf2, pts2,returnList = TRUE)
toc()

# size of the objects
object.size(pts)<object.size(pts2)
object.size(pts_buf)<object.size(pts_buf2)

使用 sf 似乎要好得多(在我的机器上大约是 0.53 秒 vs 2.1 秒)并且需要更少的内存。不过有一个异常(exception)。为什么对象 pts 比 pts2 大得多? sf 在存储点向量方面效率较低吗?

最佳答案

我能想到的一个原因:
pts ( sf ) 对象保留一个属性,为 指定几何对象的“类型”每行 .这是因为每一行都有可能成为 sf 中的不同几何图形。目的。

pts2 ( sp ) 在类 SpatialPointsDataFrame 的对象中.它只能保存点,因此不需要为每个“行”保留额外的属性

sf的前两行以对象为例,这些是与这些几何相关的属性

lapply(1:2, function(x) attributes(st_geometry(pts[x, ])))
# [[1]]
# [[1]]$names
# [1] "1"
#
# [[1]]$class
# [1] "sfc_POINT" "sfc"
#
# [[1]]$precision
# [1] 0
#
# [[1]]$bbox
# xmin ymin xmax ymax
# 81647.16 72283.90 81647.16 72283.90
#
# [[1]]$crs
# Coordinate Reference System: NA
#
# [[1]]$n_empty
# [1] 0
#
#
# [[2]]
# [[2]]$names
# [1] "2"
#
# [[2]]$class
# [1] "sfc_POINT" "sfc"
#
# [[2]]$precision
# [1] 0
#
# [[2]]$bbox
# xmin ymin xmax ymax
# 5591.116 38967.060 5591.116 38967.060
#
# [[2]]$crs
# Coordinate Reference System: NA
#
# [[2]]$n_empty
# [1] 0

每一行这个 sf data.frame 将具有类似的属性。

如果您从几何图形中剥离属性(只留下一个 data.frame)
pts_coords <- st_coordinates(pts)
pts_striped <- pts
st_geometry(pts_striped) <- NULL
pts_striped <- cbind(pts_striped, pts_coords)

然后比较对象大小
object.size(pts_striped)
# 200896
object.size(pts2)
# 203624

对象在大小上更接近

关于r - 比较简单特征 {sf} 和空间对象 {sp} : speed and memory,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49258562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com