简体   繁体   中英

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 (ie 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?

Please provide a reproducible example when you ask a question. This is very easy to do as you can build of the examples in ?extract or other help pages.

# 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM