2017-12-27 33 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

샘플링을위한 조건을 모두 지정하지 않았으므로 여기서는 몇 가지 가정을하겠습니다. 그리드 당 다각형을 샘플링하고 값을 추출 할 수 있습니다.

# 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