title: Replace mean or mode for missing values in R
body: <p>I have a large database made up of mixed data types (numeric,
  character, factor, ordinal factor) with missing values, and I am
  trying to create a for loop to substitute the missing values
  using  either the mean of the respective column if numerical or the mode if character/factor.</p>
  
  <p>This is what I have until now:</p>
  
  <pre><code>#fake array:
  age&lt;- c(5,8,10,12,NA)
  a &lt;- factor(c("aa", "bb", NA, "cc", "cc"))
  b &lt;- c("banana", "apple", "pear", "grape", NA)
  df_test &lt;- data.frame(age=age, a=a, b=b)
  df_test$b &lt;- as.character(df_test$b)
  
  for (var in 1:ncol(df_test)) {
      if (class(df_test[,var])=="numeric") {
          df_test[is.na(df_test[,var]) &lt;- mean(df_test[,var], na.rm = TRUE)
  } else if (class(df_test[,var]=="character") {
          Mode(df_test$var[is.na(df_test$var)], na.rm = TRUE)
  } 
  }
  </code></pre>
  
  <p>Where 'Mode' is the function:</p>
  
  <pre><code>Mode &lt;- function (x, na.rm) {
      xtab &lt;- table(x)
      xmode &lt;- names(which(xtab == max(xtab)))
      if (length(xmode) &gt; 1)
          xmode &lt;- "&gt;1 mode"
      return(xmode)
  }
  </code></pre>
  
  <p>It seems as it is just ignoring the statements though, without giving
  any error…
  I have also tried to work the first part out with indexes:</p>
  
  <pre><code>## create an index of missing values
  index &lt;- which(is.na(df_test)[,1], arr.ind = TRUE)
  ## calculate the row means and "duplicate" them to assign to appropriate cells
  df_test[index] &lt;- colMeans(df_test, na.rm = TRUE) [index["column",]]
  </code></pre>
  
  <p>But I get this error: "Error in colMeans(df_test, na.rm = TRUE) : 'x' must be numeric"</p>
  
  <p>Does anybody have any idea how to solve this?</p>
  
  <p>Thank you very much for all the great help!
  -f</p>