[英]How to automatically convert many fields of a polygon shapefile to raster in R
每個面與一個表的許多值相關聯。
thiessen <- readOGR(dsn = getwd(), layer = poly)
OGR data source with driver: ESRI Shapefile
Source: ".../raingauges/shp", layer: "thiessen_pol"
with 10 features
It has 5 fields
head(thiessen)
est est_name p001 p002 p003
0 2 borges 1 8 2
1 0 e018 2 4 3
2 5 starosa 5 15 1
3 6 delfim 4 2 2
4 1 e087 1 1 3
5 3 e010 0 1 0
列est和est_name與雨量計的ID和名稱有關。 以下幾列對我來說很重要,它們代表第1天,第2天等的降水量(在示例中,我僅保留了3天,但實際上,我有8年的每日降水量數據)。
我需要將多邊形轉換為柵格,但是表的每個字段(列p001,p002等)都需要一個柵格。
有一種簡單的方法可以使用R中的柵格化功能將多邊形轉換為柵格。
r_p001 <- rasterize(thiessen, r, field = thiessen$p001)
plot(r_p001)
writeRaster(r_p001, filename=".../raingauges/shp/r_p001.tif")
問題是我需要手動設置要轉換為柵格的面值的表的字段(列)。 由於我大約有2900天(每個雨量計的2900列帶有降水值),因此無法手動進行。
該文檔無助於闡明如何自動執行此過程,並且我在互聯網上找不到任何可幫助我的東西。
有誰知道如何自動將每個字段轉換為柵格並另存為tif格式?
這是一種方法:
示例數據
library(raster)
r <- raster(ncols=36, nrows=18)
p1 <- rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20))
hole <- rbind(c(-150,-20), c(-100,-10), c(-110,20), c(-150,-20))
p1 <- list(p1, hole)
p2 <- rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0))
p3 <- rbind(c(-125,0), c(0,60), c(40,5), c(15,-45), c(-125,0))
att <- data.frame(id=1:3, var1=10:12, var2=c(6,9,6))
pols <- spPolygons(p1, p2, p3, attr=att)
重要的是要有一個唯一的字段。如果您的數據沒有,請像這樣添加它
pols$id <- 1:nrow(pols)
柵格化
r <- rasterize(pols, r, field='id')
為所有其他變量創建一個圖層
x <- subs(r, data.frame(pols), by='id', which=2:ncol(pols), filename="rstr.grd")
x
#class : RasterBrick
#dimensions : 18, 36, 648, 2 (nrow, ncol, ncell, nlayers)
#resolution : 10, 10 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#data source : rstr.grd
#names : var1, var2
#min values : 10, 6
#max values : 12, 9
一種替代方法是使用“柵格屬性表”保留一層,這比較快,但是根據您的目的,也許是一種不太有用的方法:
r <- rasterize(pols, r, field='id')
f <- as.factor(r)
v <- levels(f)[[1]]
v <- cbind(v, data.frame(pols)[,-1])
levels(f) <- v
f
#class : RasterLayer
#dimensions : 18, 36, 648 (nrow, ncol, ncell)
#resolution : 10, 10 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#data source : in memory
#names : layer
#values : 1, 3 (min, max)
#attributes :
# ID var1 var2
# 1 10 6
# 2 11 9
# 3 12 6
然后,您可以執行以下操作:
z <- deratify(f)
為了獲得與第一個示例相同的結果
z
#class : RasterBrick
#dimensions : 18, 36, 648, 2 (nrow, ncol, ncell, nlayers)
#resolution : 10, 10 (x, y)
#extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
#coord. ref. : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
#data source : in memory
#names : var1, var2
#min values : 10, 6
#max values : 12, 9
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.