title: How to replace a missing value with the mean of the column values in R?
body: <p>So I have a data frame in R, lets call it datasets:</p>
  
  <pre><code>str(dataset)
  
  'data.frame':   10 obs. of  4 variables:
   $ Country  : Factor w/ 3 levels "France","Germany",..: 1 3 2 3 2 1 3 1 2 1
   $ Age      :List of 10
    ..$ : int 44
    ..$ : int 27
    ..$ : int 30
    ..$ : int 38
    ..$ : int 40
    ..$ : int 35
    ..$ : num NA
    ..$ : int 48
    ..$ : int 50
    ..$ : int 37
   $ Salary   : num  72000 48000 54000 61000 63778 ...
   $ Purchased: Factor w/ 2 levels "No","Yes": 1 2 1 1 2 2 1 2 1 2
  </code></pre>
  
  <p>I wish to replace the NA values in the Age and Salary columns with the respective means of those columns. For this, I write the following code:</p>
  
  <pre><code>dataset$Age = ifelse(is.na(dataset$Age),
                       ave(dataset$Age, FUN = function(x) mean(x, na.rm = TRUE)),
                       dataset$Age)
  
  dataset$Salary = ifelse(is.na(dataset$Salary),
                       ave(dataset$Salary, FUN = function(x) mean(x, na.rm = TRUE)),
                       dataset$Salary)
  </code></pre>
  
  <p>The above code works well for the Salary column, but throws up the following error in for the Age column:</p>
  
  <pre><code>Warning message:
  In mean.default(x, na.rm = TRUE) :
    argument is not numeric or logical: returning NA
  </code></pre>
  
  <p>I also tried to use sapply instead:</p>
  
  <pre><code>dataset$Age = ifelse(is.na(dataset$Age),
                       sapply(dataset$Age, mean, na.rm = TRUE),
                       dataset$Age)
  </code></pre>
  
  <p>Though sapply doesn't throw up any warnings, but it doesn't do the job for me as well. It simply replaces the 'na' value in the Age column with 'NaN'. Though the same code when applied for the Salary column works. </p>
  
  <p>Please help me identify where the problem is and how to make my code workable? Thanks!</p>