-
Notifications
You must be signed in to change notification settings - Fork 0
/
fill_cells.R
47 lines (29 loc) · 1.07 KB
/
fill_cells.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
### Identifying majority pixel value per polygon in R
# Required libraries
library(rgdal)
library(raster)
# Opening raster
raster_lulc = raster("raster_name.tif")
# Opening shapefile
grid_orig = readOGR("cells_name.shp")
grid_cells <- grid_orig
# Function to identify the majority class (mode)
maj.class = function(x){
uniqv <- unique(x)
uniqv[which.max(tabulate(match(x, uniqv)))]
}
# Appling function defined above in a loop for each cell
for (i in 1:length(grid_orig)){
# Cutting raster for each cell
a = crop(raster_lulc, grid_orig[i,])
# Creating data frame with the information
b = as.data.frame(a, na.rm=TRUE) #na.rm=TRUE : delete NA
# Appling the function
c = maj.class(b)
# Saving the majority class in each cell
grid_cells@data[i,paste0('maj_class')] = c
# Processing Progress
print(paste0("Cell-",i,"/",length(grid_cells)))
}
# Saving the large filled with the majority class
writeOGR(grid_cells,paste0("path_to_file/file_name.shp"), layer="file_name", driver = 'ESRI Shapefile')