I am using geological data that comes as shapefiles. However, I need them as rasters. Therefore, I convert them to categorical rasters using Terra. The data is filled with NAs for lakes, rivers, and other open water areas. I need to fill these NA cells with the nearest neighbor category or the most often seen category in the neighboring cells. Unfortunelty, focal calculates values rather than just extending the categories. I have also tried to fillholes with Terra using the polygons, but again does not compeltley fill the gaps.
For example:
r <- raster(matrix(c(rep(1, 10), 11:16), nrow = 8, ncol = 8))
r[1,1] <- NA
The NA value should be filled with 1 because the nearest values are 1.
In my real example this would be a factor. I have been stuck on this problem for a while, so any help would be appreciated.
I have tried terra::fillholes on the polygon data and terra::focal. The fillholes did not completely close the gaps and the focal calcualted values. I attempted to select modal for the focal function but it did not fill the values with the nearest sample. I cannot do interpolations because it is categorical and there are no other rasters to predict based on.
Edit:
Using the focal function in terra with the modal option did work; however, it removes the levels in your factor. If you reassign the levels using the levels command in terra, it works great! It is just something to be aware of that the categories will be lost and the output will be an integer. I kept my original data so I could just call
levels(new.raster) <- terra::levels(old.raster)
to get the levels.