Gonçalo,

Interesting question.  You can use the optim() function to optimize a
function over two dimensions.  Here's an example.

# some clumpy "cloud" data
myx <- c(0.3 + rnorm(50, 0, 0.05), 0.7 + rnorm(50, 0, 0.05))
myy <- c(0.45 + rnorm(50, 0, 0.05), 0.65 + rnorm(50, 0, 0.05))

# size of the fixed square grid
mygrid <- 0.2

# function to calculate the mean distance to the grid nodes
# the first argument, par, is the starting coordinates of the grid
calcd <- function(par, x=myx, y=myy, grid=mygrid) {
 dx <- abs((x - par[1]) %% grid)
dy <- abs((y - par[2]) %% grid)
 dx <- ifelse(dx > grid/2, grid - dx, dx)
dy <- ifelse(dy > grid/2, grid - dy, dy)
 mean(sqrt(dx^2 + dy^2))
}

# find starting coordinates that minimize the mean distance
opt <- optim(cbind(x0=mygrid/2, y0=mygrid/2), calcd)
opt$par

# look at results
library(MASS)
eqscplot(myx, myy)
abline(v=seq(from=opt$par[1], to=max(myx), by=mygrid))
abline(h=seq(from=opt$par[2], to=max(myy), by=mygrid))

Jean



On Thu, Nov 21, 2013 at 6:47 AM, Gonçalo Ferraz <gferraz29@gmail.com> wrote:

> Hi, I have a cloud of randomly distributed points in 2-dimensional space
> and want to set up a grid, with a given grid-cell size, that minimizes the
> distance between my points and the grid nodes. Does anyone know of an R
> function or toolbox that somehow addresses this problem? This is a problem
> of optimizing the location of the grid, not a problem of deciding what
> should be the grid-cell size, because size is already given. Thank you.
> Gonçalo
> ______________________________________________
> R-help@r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>

	[[alternative HTML version deleted]]

