0

I have data which looks like this:

person_id   y_var   x_var
1           98      51
1           96      90
1           57      13
2           80      38
2           14      5
3           21      28
3           18      25
3           47      41
3           72      57

Can anyone tell me how to number each person's observations sequentially in the following way? In this simplified data set the person_id is a number but in my data it is an alphanumeric factor.

person_id   instance_id y_var   x_var
1           1           98      51
1           2           96      90
1           3           57      13
2           1           80      38
2           2           14      5
3           1           21      28
3           2           18      25
3           3           47      41
3           4           72      57

Thanks.

akrun
  • 874,273
  • 37
  • 540
  • 662
steve
  • 115
  • 1
  • 7
  • `library(splitstackshape); getanID(mydf, "person.id")` should do it.... – A5C1D2H2I1M1N2O1R2T1 Jun 02 '15 at 10:52
  • Or `transform(dat, instanceid = ave(1:length(personid), personid, FUN = seq_along))`. – lukeA Jun 02 '15 at 11:03
  • @David Arenburg I don't know if a 'more canonical' duplicate would be any of these: [here](http://stackoverflow.com/questions/12925063/numbering-rows-within-groups-in-a-data-frame) or [here](http://stackoverflow.com/questions/11996135/generate-id-for-each-subset-in-dataframe). They include quite a few alternatives, not the least `ave` / `seq_along`. Perhaps add an `getanID` alternative to them? Well, well, people keep answering the mega dupes anyway... – Henrik Jun 02 '15 at 11:11
  • @Henrik OK, reopened, but I can't close it anymore. So please use your hammer on whatever dupe you feel is better before this question will receive yet another flood of answers. – David Arenburg Jun 02 '15 at 11:18
  • Thanks folks. Sorry about that. I reworded my search loads of times but didn't find what I was looking for. – steve Jun 02 '15 at 13:21

0 Answers0