title: R: Conditionally replace values in data.table column over loop
body: <p>I want to replace all values in one data.table column (col1).
  I thought to try to do it over loop but only few values are replaced.
  Example:</p>
  
  <pre><code>#Generate data.table
  library(data.table)
  dt2 &lt;- data.table(col1=rep(c("a","b","c","d"),each=2), col2=rep(c(1,2,3,4),2),col3=rep(c(1,2,3,4),2))
  &gt; dt2
     col1 col2 col3
  1:    a    1    1
  2:    a    2    2
  3:    b    3    3
  4:    b    4    4
  5:    c    1    1
  6:    c    2    2
  7:    d    3    3
  8:    d    4    4
  </code></pre>
  
  <p>Change values:</p>
  
  <pre><code>#new col1 elements
  new_col1 = c("WT","m1","m9","m10")
  #change col1
  col1_names = unique(dt$col1)
  for (i in 1:length(col1_names)){
      dt2[col1==col1_names[i],col1:=new_col1[i]]
      }
  &gt; dt2
     col1 col2 col3
  1:   WT    1    1
  2:   WT    2    2
  3:   m1    3    3
  4:   m1    4    4
  5:    c    1    1
  6:    c    2    2
  7:    d    3    3
  8:    d    4    4
  </code></pre>
  
  <p>Values in col1 are only partially replaced.
  Can anybody explain it or suggest better way how to replace?</p>
  
  <p>I tried to replace them at once but this does not work either properly:</p>
  
  <pre><code>#generate data.table
  dt2 &lt;- data.table(col1=rep(c("a","b","c","d"),each=2), col2=rep(c(1,2,3,4),2),col3=rep(c(1,2,3,4),2))
  
     col1 col2 col3
  1:    a    1    1
  2:    a    2    2
  3:    b    3    3
  4:    b    4    4
  5:    c    1    1
  6:    c    2    2
  7:    d    3    3
  8:    d    4    4
  #replace values
  col1_names = unique(dt$col1)
  dt2[col1==col1_names,col1:=new_col1]
  &gt; dt2
     col1 col2 col3
  1:   WT    1    1
  2:   m1    2    2
  3:   m9    3    3
  4:  m10    4    4
  5:   WT    1    1
  6:   m1    2    2
  7:   m9    3    3
  8:  m10    4    4
  </code></pre>
  
  <p>Values are just replaced without any condition.</p>