how ifelse (in data.table) works
<p>In my <code>data.table</code>, I wanted to numerate entries if there are more than one in each <code>by</code> group:</p>

<pre><code>dt1 &lt;- data.table(col1=1:4, col2 = c('A', 'B', 'B', 'C'))
#    col1 col2
# 1:    1    A
# 2:    2    B
# 3:    3    B
# 4:    4    C

dt1[, col3:={
  if (.N&gt;1) {paste0((1:.N), "_", col2)} else {col2};
}, by=col2]

#    col1 col2 col3
# 1:    1    A    A
# 2:    2    B  1_B
# 3:    3    B  2_B
# 4:    4    C    C
</code></pre>

<p>This works fine, but didn't work when I tried to use <code>ifelse()</code> instead:</p>

<pre><code>dt1[, col4:=ifelse (.N&gt;1, paste0((1:.N), "_", col2), col2), by=col2]
#    col1 col2 col3 col4
# 1:    1    A    A    A
# 2:    2    B  1_B  1_B
# 3:    3    B  2_B  1_B
# 4:    4    C    C    C
</code></pre>

<p>can anyone explain why?</p>