[R-sig-Geo] How to Convert extract() results to 2D matrix

Robert J. Hijmans r.hijmans at gmail.com
Fri Dec 31 18:58:24 CET 2010


Michael,

> How do I convert the extract() results, using the buffer method, to a 2D matrix
> for each point?

One way to do this now is to extract the cell numbers from a raster
with those numbers and construct the matrices from that. See example
below. To make this easier in the future, I have added a "cellnumbers"
argument to version 1.7-20 (as in extract with polygons).

library(raster)
r <- raster(ncol=180, nrow=90)

rvals <- setValues(r, runif(ncell(r)))
rcell <- setValues(r, 1:ncell(r))
xy <- cbind(-50.5, seq(-40, 40, by=20))

v <- extract(rvals, xy, buffer=1000000)
cells <- extract(rcell, xy, buffer=1000000)

m <- list()
for (i in 1:length(cells)) {
	x <- rasterFromCells(r, cells[[i]])
	y <- data.frame(cells[[i]], v[[i]])
	m[[i]] <- as.matrix(subs(x,y))
}

m


On Thu, Dec 30, 2010 at 6:43 AM, Michael ODonnell <odonnems at yahoo.com> wrote:
> I am using the extract() function within the R raster package and I am trying to
> both understand the output as well as figure out how to convert the output to a
> 2D matrix. So, I am using a SpatialPoints file and the method "buffer". The
> returned results represent rows, point location, and columns, pixel values
> extracted. Ultimately, I want to convert each record to a 2D matrix.
>
> Questions:
> How do I convert the extract() results, using the buffer method, to a 2D matrix
> for each point?
>
> Does the buffer method return pixels that fall within a radius (circle),

Yes

> and is the buffer defining a 2D array?  If extract returns pixels within a circle, does
> it assign NA to the pixels in the circle that fall outside the circle but reside
> within a 2D matrix (This is generally how most programs I work with handle
> this).

Only pixels within the circle are returned.

> What happens when a point falls near the edge of a raster dataset and the buffer
> distance exceeds the distance between the point and the edge of the raster--Are
> NAs returned or do these result in a non-square 2D array?

NAs are not returned unless the entire buffer is  outside the raster,
in which case you get a single NA value.

>
> Thank you for your help,
> Mike
>
> _______________________________________________
> R-sig-Geo mailing list
> R-sig-Geo at r-project.org
> https://stat.ethz.ch/mailman/listinfo/r-sig-geo
>



More information about the R-sig-Geo mailing list