Thanks so much!

From: Robert J. Hijmans [mailto:r.hijmans@gmail.com]
Sent: Wednesday, August 22, 2012 12:09 PM
To: Andy Bunn
Cc: R-sig-Geo@r-project.org
Subject: Re: [R-sig-Geo] raster: use extract to get data from a categorical/discrete/factor raster

Andy,

I do not that is currently available. You could the function "fourCellsFromXY" that I included below (which is part of the raster code, but not user accessible as it is declared within another function; I'll change that) and then do

four <- fourCellsFromXY(bar, foo)
e <- extract(r, as.vector(four))
m <- matrix(e, ncol=ncol(four))
apply(m, 1, modal, na.rm=T)


# using this function:
fourCellsFromXY <- function(raster, xy) {
          # should have a variant for global lon/lat data
          cells <- cellFromXY(raster, xy)
          row <- rowFromCell(raster, cells)
          col <- colFromCell(raster, cells)
          cellsXY <- xyFromCell(raster, cells)

          pos <- matrix(-1, ncol=ncol(xy), nrow=nrow(xy))
          pos[ xy[,1] > cellsXY[,1], 1 ] <- 1
          pos[ xy[,2] < cellsXY[,2], 2 ] <- 1

          poscol <- col + pos[,1]
          poscol[poscol==0] <- 2
          poscol[poscol==ncol(raster)+1] <- ncol(raster) - 1
          posrow <- row + pos[,2]
          posrow[posrow==0] <- 2
          posrow[posrow==nrow(raster)+1] <- nrow(raster) - 1

          four <- matrix(ncol=4, nrow=nrow(xy))
          four[,1] <- cells
          four[,2] <- cellFromRowCol(raster, posrow, col)
          four[,3] <- cellFromRowCol(raster, posrow, poscol)
          four[,4] <- cellFromRowCol(raster, row, poscol)
          return(four)
}



On Wed, Aug 22, 2012 at 11:28 AM, Andy Bunn <Andy.Bunn@wwu.edu<mailto:Andy.Bunn@wwu.edu>> wrote:
I have foo which is a SpatialPointsDataFrame and bar which is a raster containing land-cover data (i.e., bar is categorical).

The easiest way to extract the landcover for each point in foo is:
    extract(bar, foo, method='simple')

However, I'd like to do get the majority value from the values of the four nearest raster cells - the categorical equivalent of:
    extract(bar, foo, method='bilinear')
which is obviously the wrong move with a discrete raster.

Advice appreciated!

_______________________________________________
R-sig-Geo mailing list
R-sig-Geo@r-project.org<mailto:R-sig-Geo@r-project.org>
https://stat.ethz.ch/mailman/listinfo/r-sig-geo


	[[alternative HTML version deleted]]

