I have a data frame (3xm) with longitude, latitude and a parameter value (population density) as columns These points, long and lat, correspond to the centroids of the cells of a gridded raster. The data frame has not all of the centroids but only the ones whose cell has the parameter value different from zero.

I have the full gridded raster in addition to the data frame

How can I create using R a new raster with the same cells of the raster that I have where the values in the data frame are assigned to the cells whose coordinates are in the data frame and NaN to the other cells?

Note that the dimensions of the raster is very large

1 Answer 1


Here's a way, first I'll create a fake data set.

r <- raster(matrix(1:30, 5, 6))

## this is the full data set in data frame form
dfull <- as.data.frame(r, xy = TRUE)

## this is the partial data set, only the points with a valid value
## row-order doesn't matter, but we keep it for illustration
dpart <- dfull[sort(sample(seq_len(nrow(dfull)), 22)), ]

Now we need raster's cell-abstraction tools. Here we can treat r like an raw specification of the original raster, and in fact create it from scratch if needed. But, we have it so we use it.

rspec <- raster(r)  ## this drops the data, keeps the structure

This fills the data with missing values , because raster doesn't truly have "sparse forms", they are either empty or full and we cannot put values piece-wise into an empty raster, it's either all or nothing until it's not empty.

(Note that sparse forms are supported completely by this approach, but via a level of abstraction that is the responsibility of the user)

rspec[] <- NA_real_ 

Now we need an index into the "structure of the raster" for our points.

## these names were nominated above, and might be different for a different
## input
cells <- cellFromXY(rspec, as.matrix(dpart[, c("x", "y")])

Now, put the values in the data frame into the otherwise "filled with missing" raster.

rspec[cells] <- dpart$layer

All this is illustrated in full here: http://rpubs.com/cyclemumner/294656

It's a very powerful approach, but it's not widely understood and it's easy to get it wrong, so do use with caution and take time to practice and understand it.

Happy to help if it doesn't make sense.

Your Answer

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

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