title: How can I average two vectors only if their individual difference is less than 5 in R?
body: <p>I have a data frame that looks like this:</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>time_stamp</th>
  <th>sensor_index</th>
  <th>humidity</th>
  <th>temperature</th>
  <th>pm2.5_a</th>
  <th>pm2.5_b</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>2022-07-15 15:00:00</td>
  <td>51377</td>
  <td>37.434</td>
  <td>102.834</td>
  <td>18.209</td>
  <td>17.264</td>
  </tr>
  <tr>
  <td>2022-07-11 22:00:00</td>
  <td>51377</td>
  <td>31.267</td>
  <td>102.367</td>
  <td>7.982</td>
  <td>8.971</td>
  </tr>
  <tr>
  <td>2022-07-11 00:00:00</td>
  <td>51377</td>
  <td>43.533</td>
  <td>91.5</td>
  <td>10.518</td>
  <td>12.260</td>
  </tr>
  <tr>
  <td>2022-07-11 14:00:00</td>
  <td>51377</td>
  <td>51.433</td>
  <td>95.7</td>
  <td>14.168</td>
  <td>20.168</td>
  </tr>
  </tbody>
  </table>
  </div>
  <p>I'm trying to apply a correction factor that averages pm2.5_a and pm2.5_b if there difference is less than ±5.</p>
  <p>The formula is <code>if(pm2.5_a-pm2.5_b is &lt;±5 then 0.52*(average of pm2.5_a &amp; pm2.5_b) - 0.085*humidity + 5.71, else nothing)</code></p>
  <p>My desired output would look like this:</p>
  <div class="s-table-container">
  <table class="s-table">
  <thead>
  <tr>
  <th>time_stamp</th>
  <th>sensor_index</th>
  <th>humidity</th>
  <th>temperature</th>
  <th>pm2.5_a</th>
  <th>pm2.5_b</th>
  <th>pm_cor</th>
  </tr>
  </thead>
  <tbody>
  <tr>
  <td>2022-07-15 15:00:00</td>
  <td>51377</td>
  <td>37.434</td>
  <td>102.834</td>
  <td>18.209</td>
  <td>17.264</td>
  <td>11.75</td>
  </tr>
  <tr>
  <td>2022-07-11 22:00:00</td>
  <td>51377</td>
  <td>31.267</td>
  <td>102.367</td>
  <td>7.982</td>
  <td>8.971</td>
  <td>7.46</td>
  </tr>
  <tr>
  <td>2022-07-11 00:00:00</td>
  <td>51377</td>
  <td>43.533</td>
  <td>91.5</td>
  <td>10.518</td>
  <td>12.260</td>
  <td>7.93</td>
  </tr>
  <tr>
  <td>2022-07-11 14:00:00</td>
  <td>51377</td>
  <td>51.433</td>
  <td>95.7</td>
  <td>14.168</td>
  <td>20.168</td>
  <td></td>
  </tr>
  </tbody>
  </table>
  </div>