I am trying to populate a field in a table (or create a separate vector altogether, whichever is easier) with consecutive numbers from 1 to n, where n is the total number of records that share the same factor level, and then back to 1 for the next level, etc. That is, for a table like this

```
data<-matrix(c(rep('A',4),rep('B',3),rep('C',4),rep('D',2)),ncol=1)

```

the result should be a new column (e.g. "sample") as follows:

```
sample<-c(1,2,3,4,1,2,3,1,2,3,4,1,2)

```