从每个网格正方形的点列表中随机取点

Taking random point from list of points per grid square

下面我有一组具有位置和属性的点。 我这里有一个问题:

A​​ttr 未传递到最终 point_grid_loc

其次,我接下来要做的是从每个网格中取 1 个随机点,return 将其作为点的 data.frame 或 SpatialPointDataFrame。

纠结于如何处理它:

# Install libraries
library(sp)
library(gstat)

# Set seed for reproducible results
set.seed = 34
x <- c(5.9,6.5,7.1,3.1,5.6,8.1,6.3,5.8,2.1,8.8,5.3,6.8,9.9,2.5,5.8,9.1,2.4,2.5,9.2)
y <- c(3.6,6.5,5.4,5.2,1.1,5.1,2.7,3.8,6.07,4.4,7.3,1.8,9.2,8.5,6.8,9.3,2.5,9.2,2.5)
attr <- c(23,56,2,34,7,89,45,34,2,34,5,67,8,99,6,65,3,32,12)
initialdata <- data.frame(x,y,attr)
colnames(initialdata) <- c("x","y","attr")

# Creating SpatialPointDataFrame:
coords <- data.frame(initialdata$x,initialdata$y)
coords <- SpatialPoints(coords, proj4string=CRS(as.character(NA)), bbox = NULL)
initialdata_DF <- data.frame(coords,initialdata$attr)
initialdata_SPDF <- SpatialPointsDataFrame(coords,initialdata_DF)

#==============#
cellsize <- 3
#==============#

# Creating a grid which will constitute a mesh for stratified sampling
# Info how to include CSR p. 50 yellow book
bb<- bbox(coords)
cs <- c(cellsize,cellsize)
cc <- bb[,1] + (cs/2)
cd <- ceiling(diff(t(bb))/cs)
initialdata_grd <- GridTopology(cellcentre.offset = cc, cellsize = cs,
                                cells.dim = cd)
initialdata_SG <- SpatialGrid(initialdata_grd) # Final grid created here

# Plot the results:
plot(initialdata_SG)
plot(initialdata_SPDF, add=T,col="blue", pch="+")

# Create a polygon:
poly  <- as.SpatialPolygons.GridTopology(initialdata_grd)

# Identifies which point is in which grid/polygon location:
point_grid_loc <- data.frame(initialdata_SG,grid=over(initialdata_SPDF,poly))

我认为您在最后一步 运行 遇到了麻烦,因为您调用了错误的对象。如果您想将网格位置添加到您的空间数据,请尝试:

initialdata_SPDF$grid <- over(initialdata_SPDF, poly)

要进行采样部分,您可以使用 split/apply/combine 方法,如下所示:

# Split the spatial data into a list of data frames by grid location
gridlist <- split(initialdata_SPDF, initialdata_SPDF$grid)
# Sample one row from each data frame (grid cell) in the resulting list; see sample() help for details on that part
samples <- lapply(gridlist, function(x) x[sample(1:nrow(x), 1, FALSE),])
# Bind those rows back together in a new data frame
sampledgrid <- do.call(rbind, samples)