0

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

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

感谢您的任何帮助。

4

1 回答 1

2

您可以为此使用over(...)包中的功能sp。据我所知,你根本不需要包裹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*对象作为叠加层进行比较,并返回一个带有yin 中每个几何图形索引的向量x。在这种情况下x是一个 SpatialPoints 对象并且y是一个 SpatialPolygons 对象。因此识别与 中的每个点相关联over(...)的多边形 ID(网格单元)。其余的只是计算均值,将均值与原始数据框合并,并重命名和重新排序列,使结果看起来像您的结果。yx

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

于 2014-09-23T20:49:01.387 回答