[R] Point pattern to grid
Roger Bivand
Roger.Bivand at nhh.no
Fri Nov 18 09:39:05 CET 2005
On Thu, 17 Nov 2005, Leaf Sun wrote:
> Dear all,
>
> I'd like to change a point pattern to a grid of cells and use one of the
> variables as the output.
>
> e.g. The point pattern is of a window of (500*500) and several features
> such as pH, SoilType etc. I like to divide it into a grid with cell
> size 5*5, and use the mean of the point values falling inside the cell
> as the output.
>
> Is there any package in R working with this? Thanks in advance!
This might have been better posted on R-sig-geo. Try this:
library(sp)
df1 <- data.frame(x=runif(10000,0,500), y=runif(10000,0,500),
z=rnorm(10000))
coordinates(df1) <- c("x", "y")
summary(df1) # SpatialPointsDataFrame
grd <- GridTopology(c(2.5,2.5), c(5,5), c(100,100))
sgrd <- SpatialGrid(grd) #SpatialGrid
bbox(sgrd)
res <- overlay(sgrd, df1)
# find which grid cells the points are in
str(res)
try0 <- lapply(split(as(df1, "data.frame"), res), mean)
# take means by grid cell - assumes all numeric columns in df1
# (soil type??) - maybe write a custom function to handle non-numeric
# columns sensibly
try01 <- vector(mode="list", length=prod(slot(slot(sgrd, "grid"),
"cells.dim")))
nafill <- rep(as.numeric(NA), ncol(as(df1, "data.frame")))
try01 <- lapply(try01, function(x) nafill)
# make a container to put the means in with the right number of columns
try01[as.integer(names(try0))] <- try0
# insert means into correct list elements
try1 <- data.frame(t(data.frame(try01)))
# transpose
summary(try1)
sgrd1 <- SpatialGridDataFrame(slot(sgrd, "grid"), try1)
image(sgrd1, "x")
image(sgrd1, "y")
image(sgrd1, "z")
It goes a bit further than the short description of the sp package in the
latest R-News, and will most likely be a new method for overlay in sp. If
these are your 200K points, it may take a little longer ...
>
> Cheers,
>
> Leaf
>
>
--
Roger Bivand
Economic Geography Section, Department of Economics, Norwegian School of
Economics and Business Administration, Helleveien 30, N-5045 Bergen,
Norway. voice: +47 55 95 93 55; fax +47 55 95 95 43
e-mail: Roger.Bivand at nhh.no
More information about the R-help
mailing list