In my data.table
, I wanted to numerate entries if there are more than one in each by
group:
dt1 <- 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>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
This works fine, but didn't work when I tried to use ifelse()
instead:
dt1[, col4:=ifelse (.N>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
can anyone explain why?