代码之家  ›  专栏  ›  技术社区  ›  Ndr

从栅格单元内的光栅中提取随机点

  •  2
  • Ndr  · 技术社区  · 7 年前

    我想从每个网格单元内光栅的随机坐标中提取非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 回复  |  直到 7 年前
        1
  •  1
  •   Roman LuÅ¡trik    7 年前

    您没有指定采样的所有条件,所以我在这里进行一些假设。 可以对每个栅格多边形采样一个点并提取值。以下是您如何一蹴而就并抱着最好的希望:

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

    enter image description here

    或者可以在循环中进行,并进行采样,直到得到非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