How can I arrange matrices over arbitrary space to maximize median of sum of matrix values?
<p>I'd like to arrange 3 equivalent 10x10 matrices (<code>mesh</code>) over a 12x12 space to maximize the median of the summed values at each of the possible 169 xy coordinates (<code>median(all.coords$value, na.rm = F)</code>). In the example below, I've picked three arbitrary X Y coordinates (<code>mesh.center.coords</code>) to serve as the center of each of three meshes. </p>

<p><strong>How can I maximize <code>median(all.coords$value, na.rm = F)</code> by varying <code>mesh.center.coords</code>?</strong></p>

<p>Any solutions or thoughts on best practices would be appreciated! Thank you</p>

<pre><code>library(reshape2)
library(dplyr)
library(ggplot2)

mesh.center.coords &lt;- data.frame(x=c(2, 4, 8), y=c(1, 6, 7))

# create mesh values over 10 x 10, centered at (5,5)
set.seed(1)
mesh &lt;- data.frame(matrix(rexp(100, rate=.1), ncol=10))
colnames(mesh) &lt;- 1:10
mesh$y &lt;- 1:10

mesh.m &lt;- melt(mesh, id.vars=c("y"))
colnames(mesh.m)[2] &lt;- "x"
mesh.m$x &lt;- as.numeric(as.character(mesh.m$x)) # cleanup

# adjustment to get to assumed zero centering 
mesh.m$x &lt;- mesh.m$x-5
mesh.m$y &lt;- mesh.m$y-5

# create list to hold results of loop
list.shell &lt;- vector("list", nrow(mesh.center.coords))

# run loop to generate mesh footprints for 3 center coordinates
for(i in 1:nrow(mesh.center.coords)){
  mesh.m.temp &lt;- mesh.m
  mesh.m.temp$x &lt;- mesh.m.temp$x+mesh.center.coords[i,1]
  mesh.m.temp$y &lt;- mesh.m.temp$y+mesh.center.coords[i,2]
  list.shell[[i]] &lt;- mesh.m.temp
}

# convert list into consolidated data.frame
mesh.consol.m &lt;- do.call(rbind, list.shell) 

# sum total mesh value at each coordinate
mesh.consol.group.m &lt;- group_by(mesh.consol.m, x, y)
mesh.consol.summ.m &lt;- summarise(mesh.consol.group.m, value = sum(value))

# get rid of coordinates outside of target range (12 x 12)
mesh.consol.summ.crop.m &lt;- mesh.consol.summ.m %&gt;% filter(x&gt;=0 &amp; y&gt;=0 &amp; x &lt;= 12 &amp; y &lt;= 12)

# make lookup key for join
mesh.consol.summ.crop.m $pair &lt;- paste(mesh.consol.summ.crop.m$x, 
                                   mesh.consol.summ.crop.m$y, sep="-")
mesh.consol.summ.crop.m &lt;- mesh.consol.summ.crop.m[,3:4] # drop unneeded cols

all.coords &lt;- expand.grid(0:12, 0:12)
colnames(all.coords)[1] &lt;- "x"
colnames(all.coords)[2] &lt;- "y"
all.coords$pair &lt;- paste(all.coords$x, all.coords$y, sep="-")

all.coords &lt;- all.coords %&gt;% left_join(mesh.consol.summ.crop.m, by="pair")
all.coords[is.na(all.coords)] &lt;- 0 # NA means no mesh, convert to zero

# How can I maximize this, by varying "mesh.center.coords"?
median(all.coords$value, na.rm = F)

# For visual reference, plot of densities
ggplot()+
geom_point(data=all.coords, aes(x, y, size=value))+
scale_x_continuous(limits=c(0,12), breaks=c(0:12))+
scale_y_continuous(limits=c(0,12), breaks=c(0:12))+
ggtitle("Mesh Density")
</code></pre>