I was writing a loop with if function in R. The table is like below:
ID category 1 a 1 b 1 c 2 a 2 b 3 a 3 b 4 a 5 a
I want
looping solution will be painfully slow for bigger data. Here is one line solution using data.table:
require(data.table) a<-data.table(ID=c(1,1,1,2,2,3,3,4,5),category=c('a','b','c','a','b','a','b','a','a')) a[,':='(category_count = 1:.N),by=.(ID)]