title: Calculating weight ratios in the presence of empty cells
body: <p>I have a sample which needs to weighed in order to represent the population.</p>
  <pre><code>library(data.table)
  sample &lt;- fread(&quot;
  1,0,2,2
  3,4,3,0
  &quot;)
  
     V1 V2 V3 V4
  1:  1  0  2  2
  2:  3  4  3  0
  
  population &lt;- fread(&quot;
  10,20,20,10
  30,40,20,10
  &quot;)
  </code></pre>
  <p>This weight would simply be:</p>
  <pre><code>weights &lt;- population/sample
  
     V1  V2        V3 V4
  1: 10 Inf 10.000000  5
  2: 10  10  6.666667 Inf
  </code></pre>
  <p>However, because <code>V2</code> in <code>row 1</code> of the sample has no observations, it receives an infinite weight (Note that also <code>V4</code> in <code>row 2</code> receives an <code>Inf</code>, but this is easier to solve, because the weight is irrelevant, as there are no observations in either the sample or the population).</p>
  <p>A solution to the problem, would be to count <code>V1</code> and <code>V2</code> together in the sample and the population.</p>
  <h1>EDIT:</h1>
  <p>After some thought I realised that, for the weights to be correct, only the population values have to be adapted. If <code>V1</code> and <code>V2</code> in <code>row 1</code> of <code>population</code> are added together in <code>V1</code> of <code>population</code>, this will already lead to the correct weight for the sample observation of <code>V1 row </code>. The value of V2 becomes irrelevant because there is no observation in the sample to receive that weight.</p>
  <h1>End of EDIT</h1>
  <p>The observation would then get a weight of:</p>
  <pre><code>(population[1,1]+population[1,2])/(sample[1,1]+sample[1,2])
  
  (10+20)/(1+0)=30
  </code></pre>
  <p>In my actual data, there however many more rows, with hero and there a <code>0</code> in the sample. I am trying to figure out if there is a way to write my code, so that I do not have to do this manually..</p>
  <p>Desired outcome (notice that the weight of <code>V1</code> <code>row 1</code> is now <code>30</code>):</p>
  <blockquote>
  <p>weights</p>
  </blockquote>
  <pre><code>   V1  V2        V3 V4
  1: 30   0 10.000000  5
  2: 10  10  6.666667  0
  </code></pre>
  <h1>Attempt</h1>
  <p>I was think of doing something like:</p>
  <pre><code>for (i in seq_along(ncol(sample))) {
   lapply(population, (ifelse(sample[i]==0), population[i]&lt;-population[i+1], population[i])
  }
  </code></pre>
  <p>Where the values in the population of the cell to right will be added when the value in the sample is zero. However I am having trouble getting the syntax right, and even if it did, it does not solve the case where <code>V4</code> is <code>0</code>.</p>