title: How to fix "Error in `$<-.data.frame` replacement has x rows, data has y"?
body: <p>My goal is to make a for loop to convert some specific columns of my dataset into either factors or integers. </p>
  
  <p>The condition is going to be based on the name of the column.</p>
  
  <pre><code>
  # Here is a small reproducible dataset
  df &lt;- data.frame(x = c(10,20,30), y = c("yes", "no", "no"), z = c("Big", "Small", "Average"))
  
  # here is a vector that we are going to use inside our if statement
  column_factor_names &lt;- c("y", "z")
  
  # for each column in df
  for (i in names(df)) {
  
      print(i)
  
      # if it's a factor, convert into factor, else convert it into integer
  
      if (i %in% column_factor_names) {
          print("it's a factor")
          df$i &lt;- as.factor(df$i)
      } else {
          print("it's an integer")
          df$i &lt;- as.integer(df$i)
      }
  }
  </code></pre>
  
  <p>When I run this I get : <code>Error in `$&lt;-.data.frame`(`*tmp*`, "i", value = integer(0)) : 
    replacement has 0 rows, data has 3</code></p>
  
  <p>The problem is with the line <code>df$i &lt;- as.factor(df$i)</code> and <code>df$i &lt;- as.integer(df$i)</code> in the if-else statement.</p>
  
  <p>But what I don't understand, is that when I run this manually.
  For example:</p>
  
  <pre><code>df$"x" &lt;- as.integer(df$"x")
  df$"y" &lt;- as.factor(df$"y")
  df$"z" &lt;- as.factor(df$"z")
  
  str(df)
  </code></pre>
  
  <p>It is working:</p>
  
  <pre><code>'data.frame':   3 obs. of  3 variables:
   $ x: int  10 20 30
   $ y: Factor w/ 2 levels "no","yes": 2 1 1
   $ z: Factor w/ 3 levels "Average","Big",..: 2 3 1
  </code></pre>
  
  <p>My question is: why is it not working in the for-loop and if statement?</p>