title: aggregation of data to replace missing values of factors (categorical variables) in R by means
body: <p>Suppose i have train sample. To reproduce lets provided only 2 rows.</p>
  <pre><code>w1=structure(list(cat1 = c(1L, 1L), cat2 = c(2L, 2L), cat3 = c(3L, 
  3L), cat4 = c(4L, 4L), y = c(30L, 40L)), class = &quot;data.frame&quot;, row.names = c(NA, 
  -2L))
  </code></pre>
  <p>I have a dataset like this <code>w1</code> (cat1-cat4 are categorical variable) and Y dependent metric variable</p>
  <p>-
  however, it may be that in the dataset like <code>(w2)</code> in some categorical varible  can be represented the values that were not in the training set, for example, in the training set, in the variable cat3, there was no value of factor = 2</p>
  <pre><code>w2=structure(list(cat1 = c(1L, 1L), cat2 = c(2L, 2L), cat3 = 3:2, 
      cat4 = c(4L, 4L), y = c(30L, 40L)), class = &quot;data.frame&quot;, row.names = c(NA, 
  -2L))
  </code></pre>
  <ul>
  <li></li>
  </ul>
  <p>or it happens that in the dataset like <code>(w3)</code> in two categorical variables for example, cat2 and cat4 there are factor values ​​which were not in the train, for example, cat2 did not have a value of 3, and cat4 did not have a value of 3, but these value of factor there are in the test(w3)</p>
  <pre><code>w3=structure(list(cat1 = c(1L, 1L), cat2 = 2:3, cat3 = c(3L, 3L), 
      cat4 = 3:4, y = c(30L, 40L)), class = &quot;data.frame&quot;, row.names = c(NA, 
  -2L))
  </code></pre>
  <p>if it turns out that in the test sample the categorical variables have some value that is not in the train sample, then we calculate the average over the known categories
  eg</p>
  <pre><code>w2=structure(list(cat1 = c(1L, 1L), cat2 = c(2L, 2L), cat3 = 3:2, 
      cat4 = c(4L, 4L), y = c(30L, 40L)), class = &quot;data.frame&quot;, row.names = c(NA, 
  -2L))
  </code></pre>
  <p>then look value in train  and aggregating the well-known categories cat1, cat2, cat4 by the mean, ignoring cat3
  substitute for category for cat3 in the game 35 (30 + 40) / 2 = 35.</p>
  <pre><code>  cat1 cat2 cat3 cat4  y
  1    1    2    3    4 35
  2    1    2    3    4 40
  </code></pre>
  <p>in the case when there are no 2 categories, then we do the same</p>
  <pre><code>w3=structure(list(cat1 = c(1L, 1L), cat2 = 2:3, cat3 = c(3L, 3L), 
      cat4 = 3:4, y = c(30L, 40L)), class = &quot;data.frame&quot;, row.names = c(NA, 
  -2L))
  </code></pre>
  <p>remove cat2 and cat4 and calculate the average for cat1 and cat3</p>
  <p>according to the same principle, we remove and replace with the average all categories that are not from the trains
  Because it can be that 3 categories are missing.</p>
  <p>P.S.(there are many variable cat1 to ...catN) I just tried provide simple example.</p>