0

Possible Duplicate:
function with multiple outputs
numbering rows within groups in a data frame

G'day, I have a list of individuals that are grouped by place. I want to produce a new variable that gives a number to each individual dependant on their place. What I would like my data to look like is:

place       individual
here        1
here        2
here        3
there       1
there       2
somewhere   1 
somewhere   2

I have written this:

    nest<-data.frame(location=c("one","one","two", "three", "three", "three"))
    individual<- function(x)
      {
        pp = 1
        jj = 1
        for (i in 2:length(x)){
            if (x[i] == x[pp]){
                res<- jj+1
                pp = pp + 1
                jj = jj + 1
            }
            else{
                res<- 1
                pp = pp + 1
                jj = 1
            }
        }
        return(res)
      }

    test<- individual(nest$location)
    test

I am pretty sure this does what I want, however, I can't figure out how to return more than one result value. How, do I change this function to return a result for each value of location? Or, is there an easier way to do this with a pre-existing R package?

P.S. on a side note, I start the function from nest$individual[2] because when it starts the function from 1 and it tries to look for the previous value (which doesn't exist) it returns an error. If anyone has a thought on how to get around this I would love to hear it. Cheers.

Community
  • 1
  • 1
Adam
  • 1,147
  • 3
  • 15
  • 23

1 Answers1

0

Maybe something like this...?

ddply(nest,.(location),transform,individual = seq_len(length(location)))
  location individual
1      one          1
2      one          2
3    three          1
4    three          2
5    three          3
6      two          1

(ddply is in the plyr package)

I'm sure there are slick ways of doing this with rle as well. Indeed, just for fun:

do.call(c,lapply(rle(nest$location)[[1]],seq_len))
joran
  • 169,992
  • 32
  • 429
  • 468
  • See also http://stackoverflow.com/questions/12925063/numbering-rows-within-groups-in-a-data-frame/12925090#12925090 – mnel Oct 31 '12 at 22:17
  • @mnel Thank you, I knew there was a better duplicate out there, I just couldn't seem to find it... – joran Oct 31 '12 at 22:18
  • The question title here doesn't really reflect the question at all. – mnel Oct 31 '12 at 22:21