Zonal operation using an overlapped-ratified raster which comes from two other ratified rasters - raster

I have the following reclassify & ratified rasters that I am trying to intercept/overlay/overlap to get a new one. The idea is to get a new overlayed raster from the interception areas of the rasters R1 and R2. Once done this, I would do zonal operations. Here the R1, R2, ED rasters.
R1:
class : RasterLayer
dimensions : 1399, 1855, 2595145 (nrow, ncol, ncell)
resolution : 0.008333333, 0.008333333 (x, y)
extent : -13.69167, 1.766667, 49.86667, 61.525 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
source : memory
names : UK_GDP_2010_PPP_percapita_km2
values : 1, 6 (min, max)
attributes :
ID AG
from: 1 a
to : 6 f
R2:
class : RasterLayer
dimensions : 1399, 1855, 2595145 (nrow, ncol, ncell)
resolution : 0.008333333, 0.008333333 (x, y)
extent : -13.69167, 1.766667, 49.86667, 61.525 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
source : memory
names : layer
values : 1, 5 (min, max)
attributes :
ID AG
1 A
2 B
3 C
4 D
5 E
Here the code to intercept/overlay/overlap
1st approach
library(sf)
library(tidyverse)
R1_SPDF <- as(R1,'SpatialPolygonsDataFrame')
R1_SPDF <- st_as_sf(R1_SPDF)
R2_SPDF <- as(R2,'SpatialPolygonsDataFrame')
R2_SPDF <- st_as_sf(R2_SPDF)
R3 <- st_intersection(R1_SPDF, R2_SPDF)
R3:
Simple feature collection with 1174501 features and 2 fields
geometry type: POLYGON
dimension: XY
bbox: xmin: -8.166667 ymin: 50.01667 xmax: 1.541667 ymax: 59.55
epsg (SRID): 4326
proj4string: +proj=longlat +datum=WGS84 +no_defs
First 10 features:
UK_GDP_2010_PPP_percapita_km2 layer
1 1 1
2 1 1
2.1 1 1
3 1 1
3.1 1 1
4 1 1
4.1 1 1
1.1 1 1
5 1 1
6 1 1
geometry
1 POLYGON ((-1.641667 59.55, ...
2 POLYGON ((-1.633333 59.55, ...
2.1 POLYGON ((-1.633333 59.55, ...
3 POLYGON ((-1.625 59.55, -1....
3.1 POLYGON ((-1.625 59.55, -1....
4 POLYGON ((-1.616667 59.55, ...
4.1 POLYGON ((-1.616667 59.55, ...
1.1 POLYGON ((-1.641667 59.5416...
5 POLYGON ((-1.65 59.54167, -...
6 POLYGON ((-1.641667 59.5416...
However, I am not sure if this result is what I am looking for, because I expect a new ratified raster R3 with the overlayed areas formed with the combination/interception of R1 and R2 areas (R3 areas ratify: Aa,.. Af,…,Ea,…Ef) or something like that.
Expected R3:
class : RasterLayer
dimensions : #from intersection
resolution : 0.008333333, 0.008333333 (x, y)
extent : -13.69167, 1.766667, 49.86667, 61.525 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
names : layer
values : 1, 30 (min, max) #aproximately 30 because R1: ID=6, and R2: ID=5.
attributes :
ID AGnew
1 Aa
2 Ab
. .
. .
. .
30 Ef
Here a second try using the raster package:
2nd approach
library(raster)
R3.1 <- intersect(R1_SPDF, R2_SPDF)
R3.1:
Simple feature collection with 485611 features and 0 fields
geometry type: POLYGON
dimension: XY
bbox: xmin: -8.65 ymin: 49.875 xmax: 1.766667 ymax: 60.84167
epsg (SRID): 4326
proj4string: +proj=longlat +datum=WGS84 +no_defs
First 10 features:
geometry
1 POLYGON ((-0.9 60.84167, -0...
2 POLYGON ((-0.8916667 60.841...
3 POLYGON ((-0.8833333 60.841...
4 POLYGON ((-0.875 60.84167, ...
5 POLYGON ((-0.85 60.84167, -...
6 POLYGON ((-0.8416667 60.841...
7 POLYGON ((-0.9 60.83333, -0...
8 POLYGON ((-0.8916667 60.833...
9 POLYGON ((-0.8833333 60.833...
10 POLYGON ((-0.875 60.83333, ...
Once I got the R3, I expect to do the following zonal operation. Sum the values of ED raster within the R3 overlayed areas.
sum_R <- zonal(ED, R3, "sum")
Any recommendation is very welcome.

I think the answer in not clear at all, though I also think you already have the answer.
Perhaps your main issue here is that you are working with relative large datasets and you do not manage to see what is going on at every stage.
So for the sake of simplicity I propose a smaller instance of your problem. Notice that when asking in stackoverflow this approach may be more useful to get help. As a matter of fact your files may be too heavey to download and use in some computers, avoiding people to get involved.
But let's go to the code.
library(tidyverse)
library(raster)
library(sf)
library(tmap)
You basically have two rasters with the same resolution, location and extent as the followings:
R1 <- raster(ncol=10, nrow=10, xmn = 0, xmx=10, ymn = 0, ymx = 10)
R2 <- raster(ncol = 10, nrow = 10, xmn = 0, xmx=10, ymn = 0, ymx = 10)
values(R1) <- c(rep(1,ncell(R1)/2), rep(2,ncell(R1)/2))
values(R2) <- rep(10,ncell(R2))
with these kind of files you can perfomer directly many operations. The same extent and resolution is a plus:
Rsum <- R1 + R2
plot(R1) #See the legend of the plot
plot(R2) #See the legend of the plot
plot(Rsum) #See the legend of the plot
I do not see why you need to perform many other operation to get to a zonal operation.
It would make sense if your rasters were different. For example:
R2_Alt <- raster(ncol = 5, nrow = 2, xmn = 0, xmx=10, ymn = 0, ymx = 10) #Alt for alternative
values(R2_Alt) <- rep(10,ncell(R2))
In the case of using R2_Al a simple operation could produce a mistake:
Test <- R2_Alt + R1
So it make sense to move to vector files:
R1_sp <- as(R1, "SpatialPolygonsDataFrame")
R2_Alt_sp <- as(R2_Alt, "SpatialPolygonsDataFrame")
R1_sf <- st_as_sf(R1_sp)
R2_Alt_sf <- st_as_sf(R2_Alt_sp)
names(R1_sf)[1] <- "V1" #Just to get differente variable names
names(R2_Alt_sf)[1] <- "V2_A"
tm_shape(R1_sf) + tm_polygons(border.col = "black") +
tm_shape(R2_Alt_sf) + tm_polygons(border.col = "red", lwd = 4, alpha = 0)
And here is where having a smaller instance of your problem could shed light on your issues:
Int <- st_intersection(R2_Alt_sf, R1_sf)
View(Int)
plot(st_geometry(Int))
You can also see the outcome with the former R2 raster:
R2_sp <- as(R2, "SpatialPolygonsDataFrame")
R2_sf <- st_as_sf(R2_sp)
names(R2_Alt_sf)[1] <- "V2_A"
Int2 <- st_intersection(R2_sf,R1_sf)
Lastly, be sure that the operation you need is intersection. see
This.
I know this answer is not really an answer, but I hope that it helps you to get closer.
Let me know what you think and put here all the feedback.
all the best

Related

How to re-project a raster in r

I'm working with a raster layer that looks like this:
class : RasterLayer
dimensions : 7040, 9020, 63500800 (nrow, ncol, ncell)
resolution : 1, 1 (x, y)
extent : 0.5, 9020.5, 0.5, 7040.5 (xmin, xmax, ymin, ymax)
crs : +proj=longlat +datum=WGS84 +no_defs
source : omi_surface_no2_2005.nc
names : surface_no2_ppb
zvar : surface_no2_ppb
And I need to re-project it so that I can crop it to this shape file:
Simple feature collection with 1 feature and 0 fields
Geometry type: MULTIPOLYGON
Dimension: XY
Bounding box: xmin: -80.24869 ymin: 43.05051 xmax: -78.43696 ymax: 44.51657
Geodetic CRS: NAD83
geometry
1 MULTIPOLYGON (((-79.38536 4...
But when I try to re-project it, it doesn't work.
This is the code that I used:
omi_reproj <- projectRaster(omi, crs = crs(gtha_shp))
Has the raster layer been assigned the CRS incorrectly? I'm not sure what I'm doing wrong. If you need the data layers, I can provide a link.
Link to raster: link
This file does not follow the CF conventions for storing raster data.
library(terra)
#terra 1.7.11
x <- rast("omi_surface_no2_2005.nc")
#[1] "vobjtovarid4: **** WARNING **** I was asked to get a varid for dimension named dim1 BUT this dimension HAS NO DIMVAR! Code will probably fail at this point"
#Warning messages:
#1: In min(rs) : no non-missing arguments to min; returning Inf
#2: In min(rs) : no non-missing arguments to min; returning Inf
#3: In max(rs) : no non-missing arguments to max; returning -Inf
#4: [rast] cells are not equally spaced; extent is not defined
You can still read the values with the ncdf4 package and create a SpatRaster "by hand".
Open the ncdf file and inspect its contents
library(ncdf4)
nc <- nc_open("omi_surface_no2_2005.nc")
nc
# 3 variables (excluding dimension variables):
# double surface_no2_ppb[lon_dim,lat_dim] (Chunking: [752,587])
# double LON_CENTER[dim1,latdim] (Chunking: [1,9020])
# double LAT_CENTER[londim,dim1] (Chunking: [7040,1])
Read the relevant data and close the file
lon <- ncdf4::ncvar_get(nc, nc$var[["LON_CENTER"]])
lat <- ncdf4::ncvar_get(nc, nc$var[["LAT_CENTER"]])
d <- ncdf4::ncvar_get(nc, nc$var[["surface_no2_ppb"]])
nc_close(nc)
Create a SpatRaster
library(terra)
x <- rast(t(d[, ncol(d):1]), ext=c(range(lon), range(lat)), crs="+proj=lonlat")
plot(sqrt(x))

Converting coordinates, radius and site type data from .csv to raster in R

I am having a bit of a problem converting .csv files into raster in R... My .csv file contains coordinates (long and lat) radius (in deg) and site type. I was able to convert the coordinates into raster and was able to plot the circles using st_buffer() but I am facing two problems:
I can't convert the circles into a raster... I tried with rasterize() and fasterize() and both did not work all I'm getting is an empty raster layer
I can't seem to classify the coordinates and circles according to the site type
Any idea of what I might be doing wrong? and how can I classify my circles?
Thank you in advance!
Here is the code I used:
> head(sp_csv_data)
Longitude Latitude Radius Site_Type
1 -177.87567 -24.715167 10 MIG
2 -83.21360 14.401800 1 OBS
3 -82.59392 9.589192 1 NES
4 -82.41060 9.492750 1 NES;BRE
5 -81.17555 7.196750 5 OBS
6 -80.95770 8.852700 1 NES
##Projection systems used
rob_pacific <- "+proj=robin +lon_0=180 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs" # Best to define these first so you don't make mistakes below
longlat <- "+proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0"
####Converting to raster####
# Creating a empty raster at 0.5° resolution (you can increase the resolution to get a better border precision)
rs <- raster(ncol = 360*2, nrow = 180*2)
rs[] <- 1:ncell(rs)
crs(rs) <- CRS(longlat)
##Converting to raster
sp_raster <- rasterize(sp_csv_data[,1:2], rs, sp_csv_data[,3])
# Resampling to make sure that it's in the same resolution as sampling area
sp_raster <- resample(sp_raster, rs, resample = "ngb")
#converting into an sf spatial polygon dataframe
sp_raster <- as(sp_raster, "SpatialPolygonsDataFrame")
species_sp <- spTransform(sp_raster, CRS(longlat))
# Define a long & slim polygon that overlaps the meridian line & set its CRS to match that of world
polygon <- st_polygon(x = list(rbind(c(-0.0001, 90),
c(0, 90),
c(0, -90),
c(-0.0001, -90),
c(-0.0001, 90)))) %>%
st_sfc() %>%
st_set_crs(longlat)
# Transform the species distribution polygon object to a Pacific-centred projection polygon object
sp_robinson <- species_sp %>%
st_as_sf() %>%
st_difference(polygon) %>%
st_transform(crs = rob_pacific)
# There is a line in the middle of Antarctica. This is because we have split the map after reprojection. We need to fix this:
bbox1 <- st_bbox(sp_robinson)
bbox1[c(1,3)] <- c(-1e-5,1e-5)
polygon1 <- st_as_sfc(bbox1)
crosses1 <- sp_robinson %>%
st_intersects(polygon1) %>%
sapply(length) %>%
as.logical %>%
which
# Adding buffer 0
sp_robinson[crosses1, ] %<>%
st_buffer(0)
# Adding the circles to the coordinates
sp_robinson2 <- st_buffer(sp_robinson, dist = radius)
> print(sp_robinson2)
Simple feature collection with 143 features and 1 field
geometry type: POLYGON
dimension: XY
bbox: xmin: -17188220 ymin: -5706207 xmax: 17263210 ymax: 6179000
CRS: +proj=robin +lon_0=180 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs
First 10 features:
layer geometry
1 5 POLYGON ((3556791 4766657, ...
2 10 POLYGON ((13713529 4995696,...
3 10 POLYGON ((12834403 4946927,...
4 10 POLYGON ((9991443 4801974, ...
5 5 POLYGON ((4254202 4304190, ...
6 5 POLYGON ((11423719 4327354,...
7 10 POLYGON ((9582710 4282247, ...
8 10 POLYGON ((588877.2 4166512,...
9 5 POLYGON ((4522824 3894919, ...
10 10 POLYGON ((3828685 3886205, ...
sp_robinson3 <- fasterize(sp_robinson2, rs)
> print(sp_robinson3)
class : RasterLayer
dimensions : 360, 720, 259200 (nrow, ncol, ncell)
resolution : 0.5, 0.5 (x, y)
extent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
crs : +proj=robin +lon_0=180 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs
source : memory
names : layer
values : NA, NA (min, max)
I want to convert sp_robinson2 into a raster called sp_robinson3 but as you can see both fasterize()and rasterize()are giving me an empty raster layer...
The reason why rasterize does not work in the end is obvious: the crs of the vector and raster do not match. But can you edit your question a bit more to explain what you want to achieve? It is very odd to create a raster and then polygons and then rasterize these again. My impression is that you are making things much more complicated than need be. You also talk about circles. Which circles? I am guessing you may want circles around your points, but that is not what you are doing. It would probably be helpful to figure out things step by step, first figure out how to get the general result you want, then how to get it Pacific centered.
Below is a cleaned up version of the first part of your code. It also makes it reproducible. You need to create example in code, like this:
lon <- c(-177.87567, -83.2136, -82.59392, -82.4106, -81.17555, -80.9577)
lat <- c(-24.715167, 14.4018, 9.589192, 9.49275, 7.19675, 8.8527)
radius <- c(10, 1, 1, 1, 5, 1)
site <- c("MIG", "OBS", "NES", "NES;BRE", "OBS", "NES")
sp_csv_data <- data.frame(lon, lat, radius, site)
## cleaned up projection definitions
rob_pacific <- "+proj=robin +lon_0=180 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"
longlat <- "+proj=longlat +datum=WGS84"
##Converting to raster
# Creating a empty raster at 0.5° resolution
rs <- raster(res=0.5, crs=lonlat)
values(rs) <- 1:ncell(rs)
sp_raster <- rasterize(sp_csv_data[,1:2], rs, sp_csv_data[,3])
## makes no sense: sp_raster <- resample(sp_raster, rs, resample = "ngb")
#converting into an SpatialPolygonsDataframe
species_sp <- as(sp_raster, "SpatialPolygonsDataFrame")
## makes no sense: species_sp <- spTransform(sp_raster, CRS(longlat))

Extract location of raster pixel along a transect

I have the following raster
library(raster)
r <- raster(ncol=2421, nrow=5005)
r:
class : RasterLayer
dimensions : 2421, 5005, 12117105 (nrow, ncol, ncell)
resolution : 1, 1 (x, y)
extent : 501121, 506126, 2809088, 2811509 (xmin, xmax, ymin,
ymax)
crs : +proj=utm +zone=17 +datum=WGS84 +units=m +no_defs
+ellps=WGS84 +towgs84=0,0,0
source : E:/Datat Layers/Clip/Harney_XMerge.tif
names : Harney_XMerge
values : -3.126388e-13, 57.14 (min, max)
and the following transect in the form of polylines
Line:
class : SpatialLinesDataFrame
features : 7
extent : 500864.6, 505506.2, 2809553, 2811079 (xmin, xmax, ymin,
ymax)
crs : +proj=utm +zone=17 +datum=WGS84 +units=m +no_defs
+ellps=WGS84 +towgs84=0,0,0
variables : 3
names : OBJECTID, Id, Shape_Leng
min values : 1, 0, 2716.24783826
max values : 7, 0, 3188.64130203
I want to extract the coordinates of each pixel that falls along the transect but haven't been able to find any function that does so on my own.
I have used the following extract function but it only extracts the info from the raster in this case tree height data. Is there a way for me to use the extract function or another function to extract the UTM coordinates of each pixel that fall along my established transects?
extract(r,line )
Here is a minimal reproducible example (copied from, ?raster::extract):
library(raster)
r <- raster(ncol=36, nrow=18, vals=1)
cds1 <- rbind(c(-50,0), c(0,60), c(40,5), c(15,-45), c(-10,-25))
cds2 <- rbind(c(80,20), c(140,60), c(160,0), c(140,-55))
lines <- spLines(cds1, cds2)
extract(r, lines)
In the documentation of extract (?extract) you can see that there is an argument cellnumbers. You can do
e <- extract(r, lines, cellnumbers = TRUE)
That returns a list with, for each polyline, a matrix with cellnumbers and values. From the cellnumbers you can get the coordinates.
f <- lapply(e, function(x) xyFromCell(r, x[,1]))
Or if you prefer a data.frame
e <- extract(r, lines, cellnumbers = TRUE, df=T)
d <- data.frame(ID=e[,1], xyFromCell(r, e[,2]))
head(d)
# ID x y
#[1,] 1 -5 55
#[2,] 1 5 55
#[3,] 1 -15 45
#[4,] 1 -5 45
#[5,] 1 5 45
#[6,] 1 15 45
If you want need the points to be ordered along the line, use the extract argument along=TRUE

Reclassify values in a RasterBrick by the use of an additional Raster (Digital elevation model)

I have a RasterBrick consisting of daily snow cover data with the values 1, 2 and 3 (1= snow, 2= no snow, 3= cloud-obscured).
Example of snow cover of one day:
> snowcover
class : Large RasterBrick
dimensions : 26, 26, 2938 (nrow, ncol, nlayers)
resolution : 231, 232 (x, y)
extent : 718990, 724996, 5154964, 5160996 (xmin, xmax, ymin, ymax)
crs : +proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84
+towgs84=0,0,0
Now I wish to interpolate the cloud-obscured pixels (but only where there are less than 90 % cloud cover in a single RasterLayer, otherwise the original values should be retained for this Layers).
For spatial interpolation I want to use a digital elevation model (same study area and already in same resolution) to extract upper and lower snowline boundaries for each Layer of the RasterBrick respectively. The upper snow line represents the elevation where
all cloud-free pixels are classified as snow. The lower snowline identifies the
altitude below which all cloud-free pixels are also snow-free.
> dem
class : RasterLayer
resolution : 231, 232 (x, y)
extent : 718990.2, 724996.2, 5154964, 5160996 (xmin, xmax, ymin, ymax)
crs : +proj=utm +zone=32 +datum=WGS84 +units=m +no_defs +ellps=WGS84
+towgs84=0,0,0
values : 1503, 2135 (min, max)
For the upper snowlines I need the minimum elevation of the snow-covered pixels (value = 1). Now all pixels of value 3 in a RasterLayer of the RasterBrick above this minimum elevation, should be reclassified as value 1 (assumed to be snow-covered).
For the lower snowline on the other hand I need to identify the maximum elevation of the no-snow-pixels (value = 2). Now all pixels of value 3 in a RasterLayer of the RasterBrick above this maximum elevation should be reclassified as value 2 (assumed to be snow-free).
Is this possible using R?
I tried to make use of the overlay function, but I got stuck there.
# For the upper snowline:
overlay <- overlay(snowcover, dem, fun=function(x,y){ x[y>=minValue(y[x == 1])] <- 1; x})
Here is some example data
library(raster)
dem <- raster(ncol=8, nrow=7, xmn=720145, xmx=721993, ymn=5158211, ymx=5159835, crs='+proj=utm +zone=32 +datum=WGS84')
values(dem) <- ncell(dem):1
snow <- setValues(dem, c(1, 1, rep(1:3, each=18)))
snow[,c(2,5)] <- NA
snow[3] <- 3
plot(snow)
lines(as(dem, 'SpatialPolygons'))
text(dem)
The plot shows the snow classes (1, 2, 3) with the elevation values on top.
We can use mask, but need to deal with the missing values.
msnow <- reclassify(snow, cbind(NA, 0))
# mask to get only the snow elevations
x <- mask(dem, msnow, maskvalue=1, inverse=TRUE)
# minimum elevation of the snow-covered cells
minsnow <- minValue(x)
minsnow
#[1] 37
# snow elevation = 1
snowy <- reclassify(dem, rbind(c(-Inf, minsnow, NA), c(minsnow, Inf, 1)))
newsnow <- cover(snow, snowy)
s <- stack(dem, snow, newsnow)
names(s) <- c("elevation", "old_snow", "new_snow")
You were very close, as you can do
r <- overlay(dem, snow, fun=function(e, s){ s[e >= minsnow] <- 1; s})
But note that that also overwrites high cells with no snow.
Which could be fixed like this:
r <- overlay(dem, snow, fun=function(e, s){ s[e >= minsnow & is.na(s)] <- 1; s})
To select layers with more than x% cells with value 3 (here I use a threshold of 34%):
threshold = .34
s <- stack(snow, snow+1, snow+2)
f <- freq(snow)
f
# value count
#[1,] 1 14
#[2,] 2 13
#[3,] 3 15
#[4,] NA 14
nas <- f[is.na(f[,1]), 2]
ss <- subs(s, data.frame(from=3, to=1, subsWithNA=TRUE))
cs <- cellStats(ss, sum)
csf <- cs / (ncell(snow) - nas)
csf
# layer.1 layer.2 layer.3
#0.3571429 0.3095238 0.3333333
i <- which(csf < threshold)
use <- s[[i]]
#use
class : RasterStack
dimensions : 7, 8, 56, 2 (nrow, ncol, ncell, nlayers)
resolution : 231, 232 (x, y)
extent : 720145, 721993, 5158211, 5159835 (xmin, xmax, ymin, ymax)
coord. ref. : +proj=utm +zone=32 +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
names : layer.2, layer.3
min values : 2, 3
max values : 4, 5

How to automatically convert many fields of a polygon shapefile to raster in R

I have a shapefile representing Thiessen polygons.
Each polygon is associated with many values of a table.
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
The columns 'est' and 'est_name' are related to the ID and name of the rain gauges. The following columns are important to me and represent precipitation values on day 1, 2, and so on (in the exemple I kept just three days, but actually, I have 8 years of daily precipitation data).
I need to convert the polygons to raster, but one raster for each field (column p001, p002, and so on) of the table.
There is a simple way to convert polygons to raster with the function rasterize in R.
r_p001 <- rasterize(thiessen, r, field = thiessen$p001)
plot(r_p001)
writeRaster(r_p001, filename=".../raingauges/shp/r_p001.tif")
The problem is that I need to set manually the field (column) of the table with the polygon values to be converted to raster. As I have about 2900 days (2900 columns with precipitation values for each rain gauge), it is impossible to do manually.
The documentation does not help to clarify how to automate this process and I did not find anything on the internet to help me.
Does anyone know how to automatically convert each field to raster and save as tif format?
Here is an approach:
Example data
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)
The important thing is to have a field with a unique If your data do not have it, add it like this
pols$id <- 1:nrow(pols)
Rasterize
r <- rasterize(pols, r, field='id')
Create a layer for all other variables
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
An alternative is to keep one layer with Raster Attribute Table, that is quicker, but depending on your purpose, perhaps a less useful method:
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
You can then do:
z <- deratify(f)
To get the same result as in the first example
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

Resources