How do I impute missing variables in R using dplyr?
<p>I would like to impute missing values for a variable given the existing values.
In <code>var2</code>, we notice that there are a lot of <code>NA</code>s. </p>

<ol>
<li>If any 2 ids are the same, then their values for <code>var2</code> are the same.</li>
<li>If the id has no values for <code>var2</code>, like in the case of id==2, then we just output as <code>NA</code>.</li>
</ol>

<p>It should look from <code>df_old</code> to <code>df_new.</code></p>

<pre><code> df_old&lt;- read.table(header = TRUE, text = "
 id  var1  var2 
  1  A       12    
  1  B       NA    
  1  E       NA    
  2  G       NA
  2  J       NA
 ")

df_new&lt;- read.table(header = TRUE, text = "
id  var1  var2 
 1  A       12    
 1  B       12    
 1  E       12    
 2  G       NA
 2  J       NA
")
</code></pre>

<p>I tried take:</p>

<pre><code>df_new&lt;-df_old %&gt;%
        group_by(id) %&gt;%
        mutate(var2=na.omit(var2))
</code></pre>

<p>I believe it doesn't work because of the second case. I was also wondering if using ifelse would be okay. Need help thanks!</p>