Not sure how to formulate the question in words, but how can I create an index-column for a data.table that per group increments when a different value appear?
Here is the MWE
library(data.table)
in.data <- data.table(fruits=c(rep("banana", 4), rep("pear", 5)),vendor=c("a", "b", "b", "c", "d", "d", "e", "f", "f"))
Here is the result the R-code should generate
in.data[, wanted.column:=c(1,2,2,3,1,1,2,3,3)]
# fruits vendor wanted.column
# 1: banana a 1
# 2: banana b 2
# 3: banana b 2
# 4: banana c 3
# 5: pear d 1
# 6: pear d 1
# 7: pear e 2
# 8: pear f 3
# 9: pear f 3
So it labels each vendor 1, 2, 3, ... within each fruit. There is probably a very simple solution, but I'm stuck.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…