title: Look up table using large raster (in R)
body: <p>Really hope you can help me out. Thank you in advance, for everything I've learned from these pages up to this point. And apologies, my know-how is limited by the part-time nature at which i'm attempting to learn all there is in R.</p>
  
  <p>My Aim:
  Look up table inversion using (large) rasters.</p>
  
  <p>What I have at the moment:</p>
  
  <pre><code>#Observed data (in this case just as a dataframe)
  obs &lt;- data.frame(runif(100,0,1))
  
  #Two sets of simulated data (often n &gt;10 000)
  sim.A &lt;- data.frame(runif(1000,0,1))
  
  sim.B &lt;- data.frame(runif(1000,0,1))
  
  #Calculate the error [cost] for each observed value and every simulated(A) value
  error.fun &lt;- function(x){sqrt((x-sim.A)^2)}              
  error &lt;- apply(obs,1,error.fun) 
  
  #Find the position of the min [error] value
  min.func &lt;- function(x){which(x == min(x),arr.ind = F)}    
  cost.min &lt;- apply(error,2,min.func)
  
  #Subset the simulated (B) dataset at the position of the least error[cost.min]
  LUT.values = data.frame(sim.B[cost.min,])
  </code></pre>
  
  <p>My Problem(s):</p>
  
  <p>1) The code above works for samples extracted from the raster. But, I need to replace sampled observations with an entire (ncell > 1Mil) raster. I obviously need to optimize the above two functions (into one?), but the closest I've got leaves me skeptical as the results are poor compared to the sampled data attempts.</p>
  
  <p>My Attempt for large rasters:</p>
  
  <pre><code>#This runs, but I dont think it's working correctly
  
  crs.UTM &lt;- CRS("+proj=utm +zone=36 +south +datum=WGS84 +units=m +no_defs+ellps=WGS84 +towgs84=0,0,0")
  r &lt;- raster( crs=crs.UTM)
  extent(r) &lt;- extent(0, 100, 0, 100) 
  res(r) &lt;- c(1, 1)
  values(r) &lt;- runif(ncell(r), 0, 1)
  
  #Simulated data (often n &gt;10 000)
  sim.A &lt;- data.frame(runif(1000,0,1))
  
  sim.B &lt;- data.frame(runif(1000,0,1))
  
  cost.min.func &lt;- function(x){
  cost &lt;- sqrt((x-sim.A)^2)     
  c.min &lt;- sim.B[which(cost == min(cost),arr.ind = FALSE),]}
  
  LUT.rst &lt;- calc(r,cost.min.func)
  </code></pre>
  
  <p>Many Thanks</p>