[R-sig-Geo] over() in sp package

Robert J. Hijmans r.hijmans at gmail.com
Tue Apr 14 02:44:55 CEST 2015


Kenny,

Here is an alternative route

library(raster)
states <- shapefile("cb_2013_us_state_20m.shp")
tMaxGrid <- raster(unzippedFiles[1])
x <- extract(tMaxGrid, states)

This returns a list of the length of states. Each list element has a
vector with the grid cell values.

For a mean do

xs <- extract(tMaxGrid, states, fun=mean)

See ?extract for weights

Robert

On Mon, Apr 13, 2015 at 4:27 PM, Kenny Bell <kmb56 at berkeley.edu> wrote:
> Hi,
>
> When I call:
>
> over(spPolyDf, spGridDf)
>
> The function seems to be returning the spGridDf$band1 value for the first
> grid cell that is contained in each polygon.
>
> What I would like is an overlap-area weighted average (or some provided
> function like sum) of all the grid cells contained (or partially contained)
> in each polygon element of spPolyDf.
>
> I have code that does this by eventually using joinPolys() from PBSMapping,
> but it's slow and would be much cleaner to have a sp-only solution. Is
> there any way to do this? Some example code is below:
>
> library(sp)
> library(rgdal)
>
> # Download a USA shapefile
> tmpFile <- tempfile()
> download.file("
> http://www2.census.gov/geo/tiger/GENZ2013/cb_2013_us_state_20m.zip",
> destfile = tmpFile)
> unzipped <- unzip(zipfile = tmpFile, exdir = getwd())
>
> # This is the actual reading stage
> states <- readOGR(getwd(), layer="cb_2013_us_state_20m")
>
> # Remove all the files on disk
> file.remove(tmpFile)
> file.remove(unzipped)
>
> tmpFile <- tempfile()
>
> url <- paste0("http://www.prism.oregonstate.edu/fetchData.php?type",
>               "=bil&kind=recent&elem=tmax&range=daily&temporal=",
>               "20140416")
>
> # Download the file to fileName
> download.file(url = url, mode = "wb", destfile = tmpFile)
>
> # unzip the file to the working directory.
> unzippedFiles <- unzip(zipfile = tmpFile, overwrite = TRUE)
>
> # read into R
> tMaxGrid <- readGDAL(fname = unzippedFiles[1])
>
> # delete the file
> file.remove(tmpFile)
> file.remove(unzippedFiles)
>
> # This doesn't work correctly
> states$tmax20140416 <- over(states, tMaxGrid)
>
>         [[alternative HTML version deleted]]
>
> _______________________________________________
> 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