user3493038
user3493038

Reputation: 25

Extract xy coordinates from raster using buffer function

I have some xy coordinates as a SpatialPoints (points) object and have used them to extract temperature values at these locations from a RasterLayer (raster):

extract = extract(raster, points)

However several of the points are falling outside of the raster layer (i.e. not plotting on land) and I want to use the buffer argument to expand the radius around each point by 10000m -

extract2 = extract(raster, points, method="simple",buffer=10000, cellnumbers=TRUE)

This produces a "list" object i.e.- 

head(extract2)

[[1]]
  cell  value 
591332    165 

[[2]]
  cell  value 
475809     NA 

[[3]]
  cell  value 
534127     NA 

[[4]]
  cell  value 
534127     NA 

[[5]]
  cell  value 
534127     NA 

[[6]]
  cell  value 
534127     NA 

but I would like to create a dataframe where I have the raster values at the point locations (either NA or a temperature value) and the cell numbers so I can access the original xy coordinates for the cells of interest in the raster layer. How can I do this?

Upvotes: 1

Views: 1723

Answers (1)

Robert Hijmans
Robert Hijmans

Reputation: 47146

Here is a reproducible example from ?extract.

# example data
r <- raster(ncol=36, nrow=18, crs='+proj=utm +zone=14 +datum=WGS84')
r[] <- 1:ncell(r)
xy <- cbind(x=-50, y=seq(-80, 80, by=20))

# extract
e <- extract(r, xy, buffer=10)
ee <- t(data.frame(e))
rownames(ee) <- NULL

data.frame(xy, ee)

The above works in many cases, but not around edges or with lon/lat data as there might be a varying number of cells. In such cases you might do:

 e <- extract(r, xy, buffer=10)
 m <- max(sapply(e, length))
 x <- rep(NA, m)
 ee <- t(sapply(e, function(y) {x[1:length(y)] <- y; x}))
 data.frame(xy, ee)

Upvotes: 0

Related Questions