从网格单元内的栅格中提取随机点
Extracting random points from a raster within a grid cell
我想从每个网格单元内的栅格的随机坐标中提取非 NA 值。
栅格示例
library(raster)
r <- raster(ncol = 10, nrow = 10, xmx = -80, xmn = -150, ymn = 20, ymx = 60)
values(r) <- runif(ncell(r))
网格示例
grid <- raster(extent(r))
res(grid) <- 15
proj4string(grid)<- proj4string(r)
gridpolygon <- rasterToPolygons(grid)
plot(r)
plot(gridpolygon, add = T)
如何为每个网格单元内的每个栅格部分提取具有随机坐标的值?
我对这类东西真的很陌生,所以非常欢迎任何建议。
谢谢
您没有指定抽样的所有条件,所以我在这里进行一些假设。
可以对每个网格多边形采样一个点并提取值。以下是您如何一次性完成并希望获得最佳结果:
# pick random points per each grid cell and plot
set.seed(357)
pickpts <- sapply(gridpolygon@polygons, spsample, n = 1, type = "random")
sapply(pickpts, plot, add = TRUE)
# extract values of raster cells at specified points
sapply(pickpts, FUN = extract, x = r)
或者您可以循环执行并采样,直到获得非 NA 值。
N <- length(gridpolygon@polygons)
result <- rep(NA, times = N)
for (i in 1:N) {
message(sprintf("Trying polygon %d", i))
pl <- gridpolygon@polygons[[i]]
candval <- result[i] # start with NA
# sample until you get a non-NA hit
while (is.na(candval)) {
pickpoint <- spsample(pl, n = 1, type = "random")
candval <- extract(x = r, y = pickpoint)
}
result[i] <- candval
}
result
[1] 0.4235214 0.6081435 0.9126583 0.1710365 0.7788590 0.9413206 0.8589753
[8] 0.0376722 0.9662231 0.1421353 0.0804440 0.1969363 0.1519467 0.1398272
[15] 0.4783207
我想从每个网格单元内的栅格的随机坐标中提取非 NA 值。
栅格示例
library(raster)
r <- raster(ncol = 10, nrow = 10, xmx = -80, xmn = -150, ymn = 20, ymx = 60)
values(r) <- runif(ncell(r))
网格示例
grid <- raster(extent(r))
res(grid) <- 15
proj4string(grid)<- proj4string(r)
gridpolygon <- rasterToPolygons(grid)
plot(r)
plot(gridpolygon, add = T)
如何为每个网格单元内的每个栅格部分提取具有随机坐标的值?
我对这类东西真的很陌生,所以非常欢迎任何建议。 谢谢
您没有指定抽样的所有条件,所以我在这里进行一些假设。 可以对每个网格多边形采样一个点并提取值。以下是您如何一次性完成并希望获得最佳结果:
# pick random points per each grid cell and plot
set.seed(357)
pickpts <- sapply(gridpolygon@polygons, spsample, n = 1, type = "random")
sapply(pickpts, plot, add = TRUE)
# extract values of raster cells at specified points
sapply(pickpts, FUN = extract, x = r)
或者您可以循环执行并采样,直到获得非 NA 值。
N <- length(gridpolygon@polygons)
result <- rep(NA, times = N)
for (i in 1:N) {
message(sprintf("Trying polygon %d", i))
pl <- gridpolygon@polygons[[i]]
candval <- result[i] # start with NA
# sample until you get a non-NA hit
while (is.na(candval)) {
pickpoint <- spsample(pl, n = 1, type = "random")
candval <- extract(x = r, y = pickpoint)
}
result[i] <- candval
}
result
[1] 0.4235214 0.6081435 0.9126583 0.1710365 0.7788590 0.9413206 0.8589753
[8] 0.0376722 0.9662231 0.1421353 0.0804440 0.1969363 0.1519467 0.1398272
[15] 0.4783207