title: Replacing missing data in a categorical variable in R
body: <p>I am not sure how I can write a function to replace NA data in a series of categorical vectors.</p>
  
  <p>Consider the following: I have a categorical vector which contains NA data and I want to replace the NA data according to the proportion of the existing data.</p>
  
  <p>For example, </p>
  
  <pre><code>a&lt;-factor(c("yes","no","no","yes","yes","yes","no","yes","yes","yes","yes","yes",NA, NA))
  </code></pre>
  
  <p>I wrote the following code:</p>
  
  <pre><code>a[is.na(a)]&lt;-sample(c("yes","no"),sum(is.na(a)),replace=TRUE,
  prob=c(sum(na.omit(a=="yes"))/sum(!is.na(a)),sum(na.omit(a=="no"))/sum(!is.na(a)))) 
  
  ## replace NA with yes or no according to the proportion of yes/no in the non-NA data
  </code></pre>
  
  <p>The above code works fine but now I have a dataframe which contains many categorical variables.
  For example:</p>
  
  <pre><code>a&lt;-c("yes","no","no","yes","yes","yes","no","yes","yes","yes","yes","yes",NA, NA)
  b&lt;-c("red","blue","white","red","blue","red","blue","red","blue","red","blue",NA,NA,NA)
  c&lt;-c(1,3,2,1,2,3,1,2,3,1,2,3,NA,NA)
  
  a&lt;-as.factor(a)   ## ensure the vectors are treated as categorical variable
  b&lt;-as.factor(b)
  c&lt;-as.factor(c)
  
  df&lt;-data.frame(a=a,b=b,c=c)
  </code></pre>
  
  <p>I am struggling in writing a function that would allow me to replace NA data in all categorical variables in such dataframe.   Please note that each variable may have more than two categories.</p>