3
我的以下問題建立在這個帖子上提出@jbaums解決方案:Global Raster of geographic distances如何基於網格細胞子集柵格值
爲了再現例子的目的,我有距離到的柵格數據集最近的海岸線:
library(rasterVis); library(raster); library(maptools)
data(wrld_simpl)
# Create a raster template for rasterizing the polys.
r <- raster(xmn=-180, xmx=180, ymn=-90, ymx=90, res=1)
# Rasterize and set land pixels to NA
r2 <- rasterize(wrld_simpl, r, 1)
r3 <- mask(is.na(r2), r2, maskvalue=1, updatevalue=NA)
# Calculate distance to nearest non-NA pixel
d <- distance(r3) # if claculating distances on land instead of ocean: d <- distance(r3)
# Optionally set non-land pixels to NA (otherwise values are "distance to non-land")
d <- d*r2
levelplot(d/1000, margin=FALSE, at=seq(0, maxValue(d)/1000, length=100),colorkey=list(height=0.6), main='Distance to coast (km)')
的數據是這樣的:
從這裏,我需要子集距離柵格(d),或創建一個新的光柵,僅包含細胞距離海岸線不到200公里。我試圖使用getValues()來確定值爲< = 200(如下所示)的單元格,但目前爲止沒有成功。誰能幫忙?我在正確的軌道上嗎?
#vector of desired cell numbers
my.pts <- which(getValues(d) <= 200)
# create raster the same size as d filled with NAs
bar <- raster(ncols=ncol(d), nrows=nrow(d), res=res(d))
bar[] <- NA
# replace the values with those in d
bar[my.pts] <- d[my.pts]
太棒了!有用。謝謝@Ouistiti! – fabfab