r - Taking random point from list of points per grid square -
below have set of points locations , attributes. have 1 problem here:
the attr not passed final point_grid_loc
secondly, want do next take 1 random point each grid , return data.frame or spatialpointdataframe of points.
struggling how approach it:
# install libraries library(sp) library(gstat) # set seed 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 grid constitute mesh stratified sampling # info how 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 results: plot(initialdata_sg) plot(initialdata_spdf, add=t,col="blue", pch="+") # create polygon: poly <- as.spatialpolygons.gridtopology(initialdata_grd) # identifies point in grid/polygon location: point_grid_loc <- data.frame(initialdata_sg,grid=over(initialdata_spdf,poly))
i think you're running trouble @ last step because you're calling wrong object. if want add grid location spatial data, try:
initialdata_spdf$grid <- over(initialdata_spdf, poly)
to sampling part, can use split/apply/combine approach, this:
# split spatial data list of data frames grid location gridlist <- split(initialdata_spdf, initialdata_spdf$grid) # sample 1 row each data frame (grid cell) in resulting list; see sample() details on part samples <- lapply(gridlist, function(x) x[sample(1:nrow(x), 1, false),]) # bind rows in new data frame sampledgrid <- do.call(rbind, samples)
Comments
Post a Comment