for loop & if function in R

后端 未结 3 1599
刺人心
刺人心 2021-01-27 19:22

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

3条回答
  •  -上瘾入骨i
    2021-01-27 19:41

    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)]
    

提交回复
热议问题