2015-09-30 210 views
0

下面我有一組包含位置和屬性的點。 我有一個問題在這裏:從每個網格點的點列表中取出隨機點

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

回答

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) 
+0

奇等簡潔,您的幫助非常感謝! – MIH

+0

我還有一個問題。在 樣本中,如果我用2替換1個樣本,則R返回消息: 錯誤代碼(網格列表函數(x)x [樣本(1:nrow(x),1,FALSE),]) sample.int(x,大小,替換,概率): 當'replace = FALSE'時不能取大於樣本的樣本 我想抽樣而不替換,似乎樣本大小1沒有在網格廣場內沒有點的時候出現問題。任何猜測如何去使它成爲可能? IE瀏覽器。對於樣本大小= 2,如果網格中有1個樣本,則只返回1點,如果沒有任何內容,則返回1。 – MIH

+1

你應該能夠在調用'lapply()'的函數中使用'if'和'else'結構來處理它,例如'lapply(gridlist,function(x)if(nrow(x) > 1){x [sample(1:nrow(x),2,FALSE),]} else {x [sample(1:nrow(x),1,FALSE),]})'。 – ulfelder