I have a data set of this format
User
1
2
3
2
3
1
1
Now I want to add a column saying count which counts the occurrence of the user. I want output in the below format.
User Count
1 1
2 1
3 1
2 2
3 2
1 2
1 3
I have few solutions but all those solutions are somewhat slow.
My data.frame has 100,000 rows now and soon it may go up to 1 million. I need a solution which is also fast.
This is fairly easy with
ave
andseq.int
:This is a common strategy and is often used when the items are adjacent to each other. The second argument is the grouping variable and in this case the first argument is really kind of a dummy argument since the only thing that it contributes is a length, and it is not a requirement for
ave
to have adjacent rows for the values determined within groupings.You can use
getanID
from my "splitstackshape" package:This is essentially an approach with "data.table" that looks something like the following:
An option using
dplyr
Using
sqldf