I have soil data rasters from SoilGrids.org that have some small holes with NA cells (White spaces in the image) that I want to fill using some interpolation method to get a more spatially continuous raster for further analysis. I have found some options in SAGA (e.g. Close gaps) and GRASS (e.g. r.fillnulls) that seems to do the job but I am having problems to implement them in my workflow in R. I have found meteo::rfillspgaps , but it takes too much time and seems to never ends.

Is there any other function or solution in R?

enter image description here


2 Answers 2


I've only found two ways. The ideal but computationally heavy way is to convert the raster to SpatialPixels and then use idw() or krige() in gstats package for interpolation, and convert back to raster.

The quick and dirty way is to use focal in the raster package with fun=mean, NAonly=T, na.rm=T and an appropriately sized matrix of 1's as the weights.


It's nearly a year old but thought I'd throw in another option.

The approxNA function from the raster package works if you have several Raster objects in a RasterBrick or RasterStack, rather than an individual raster. The reason is that it will use the information in the other raster layers to interpolate what an NA might be, so it works well for raster data that changes across time, and if the time between raster layers is very short (i.e. hours, a few days, a week), such as Chlorophyll concentration or sea surface temperature (which is what I use and why it worked for me). This does imply that coarse temporal resolution between raster layers would lead to less accurate interpolations of missing data. If you've got several soil layers of the same place with very fine temporal resolution (hours/days/weeks), it could work. You would only need to specify the RasterBrick or RasterStack object, as the default method is set to linear (the other option is constant), while the default options for all the other arguments seem to work pretty well, too.

If you don't have several layers, you could try to using the focal function, also from the raster package. It uses a combination of a moving window to look at neighboring cells and a matrix of weights to interpolate missing data. Full Disclaimer: I have not used this before and not sure how it work (or how fast it'll process).

Update: Added a small note about considering temporal resolution when using the approxNA function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.