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

时间:2015-09-30 09:30:56

标签: r random grid points

下面我有一组包含位置和属性的点。 我有一个问题:

Attr未传递到最终point_grid_loc

其次,我接下来要做的是从每个网格中取1个随机点并将其作为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))

1 个答案:

答案 0 :(得分:2)

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

initialdata_SPDF$grid <- over(initialdata_SPDF, poly)

要执行采样部分,您可以使用拆分/应用/合并方法,如下所示:

# 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)