2017-12-27 16 views
2

各グリッドセル内のラスタのランダム座標から非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) 

がどのように各グリッドセル内の各ラスタ部分に対するランダム座標値を抽出することができる、グリッドの例の一例?

私はこの種のもので本当に新しいので、どんな提案も大歓迎です。おかげさまで

答えて

1

サンプリングの条件をすべて指定していないため、ここではいくつかの前提があります。 グリッド1ポリゴンあたりのポイントをサンプリングして値を抽出することができます。ここでは、あなたが最良のために一度と希望でそれを行うことができます方法は次のとおりです。

# pick random points per each grid cell and plot 
set.seed(357) 
pickpts <- sapply([email protected], spsample, n = 1, type = "random") 
sapply(pickpts, plot, add = TRUE) 

# extract values of raster cells at specified points 
sapply(pickpts, FUN = extract, x = r) 

enter image description here

それとも、非NA値を取得するまでは、ループやサンプルでそれを行うことができます。

N <- length([email protected]) 
result <- rep(NA, times = N) 

for (i in 1:N) { 
    message(sprintf("Trying polygon %d", i)) 

    pl <- [email protected][[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 
関連する問題