【问题标题】:Analyze data for spatial join (points to grid) and generate new dataset in R分析空间连接的数据(点到网格)并在 R 中生成新数据集
【发布时间】:2014-09-23 18:20:59
【问题描述】:

我有一个数据集,其中包含经度/纬度点和每组坐标的结果值。我想创建一个空间网格,然后对同一网格中的坐标取结果的平均值,并生成一个新的数据框,为每个坐标分配一个网格编号并具有平均结果。例如,从这段代码开始:

require(sp)
require(raster)

frame <- data.frame(x = c(7.5, 8.2, 8.3), y = c(1,4,4.5), z = c(10,15,30))

coordinates(frame) <- c("x", "y")
proj4string(frame) <- CRS("+proj=longlat")

grid <- GridTopology(cellcentre.offset= c(0,0), cellsize = c(2,2), cells.dim = c(5,5))
sg <- SpatialGrid(grid)
poly <- as.SpatialPolygons.GridTopology(grid)
proj4string(poly) <-  CRS("+proj=longlat")

plot(poly)
text(coordinates(poly), labels = row.names(poly), col = "gray", cex. =.6)
points(frame$x, frame$y, col = "blue", cex = .8)

然后我想对网格单元中的结果 (z) 进行平均,并生成一个如下所示的数据框(例如观察):

    x   y  z grid grid_mean
1 7.5 1.0 10   g20      10
2 8.2 4.0 15   g15     22.5
3 8.3 4.5 30   g15     22.5

感谢您的任何帮助。

【问题讨论】:

  • 您提供的代码将第一个点放在 g20 和 g25 之间的边界上,而不是在 g10 中。你确定网格是你想要的吗?另外,你想如何处理边界上的点??
  • 感谢您的关注。我在g20上列出了它;对于边界点,我更喜欢随机分配。

标签: r spatial r-grid


【解决方案1】:

您可以为此使用包sp 中的over(...) 函数。据我所知,您根本不需要包raster

require(sp)

frame  <- data.frame(x = c(7.5, 8.2, 8.3), y = c(1,4,4.5), z = c(10,15,30))
points <- SpatialPoints(frame)
proj4string(points) <-  CRS("+proj=longlat")

grid  <- GridTopology(cellcentre.offset= c(0,0), cellsize = c(2,2), cells.dim = c(5,5))
sg    <- SpatialGrid(grid)
poly  <- as.SpatialPolygons.GridTopology(grid)
proj4string(poly) <-  CRS("+proj=longlat")

# identify grids...
result <- data.frame(frame,grid=over(points,poly))
# calculate means...
result <- merge(result,aggregate(z~grid,result,mean),by="grid")
# rename and reorder columns to make it look like your result
colnames(result) <- c("grid","x","y","z","grid_mean")
result <- result[,c(2,3,4,1,5)]
result
#     x   y  z grid grid_mean
# 1 8.2 4.0 15   15      22.5
# 2 8.3 4.5 30   15      22.5
# 3 7.5 1.0 10   25      10.0

over(x,y,...) 函数将两个Spatial* 对象作为叠加层进行比较,并返回一个向量,该向量带有y 中每个几何图形的y 的索引x。在这种情况下,x 是一个 SpatialPoints 对象,y 是一个 SpatialPolygons 对象。所以over(...) 标识了y 中与x 中的每个点相关联的多边形ID(网格单元)。其余的只是计算均值,将均值与原始数据框合并,并重命名和重新排序列,使结果看起来像您的结果。

我稍微调整了您的代码,因为它没有意义:您创建一个带有 z 值的数据框,然后将其转换为 SpatialPoints 对象,该对象会丢弃 z 值...

【讨论】:

  • 太好了,谢谢 - 这正是我想要的。
猜你喜欢
  • 2015-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-20
  • 1970-01-01
  • 1970-01-01
  • 2012-01-23
  • 2014-09-02
相关资源
最近更新 更多