Skip to content
Prev 309409 / 398506 Next

help with for loop: new column giving count of observation for each SITEID

Not quite,
 I need it like this, a new number for each ordered year in the sequence within each site, regardless of what the years are,  and to retain the RchID column.

RchID	site	year	index
1	A	2002	1
2	A	2004	2
3	A	2005	3
4	B	2003	1
5	B	2006	2
6	B	2008	3
7	C	2002	1
8	C	2003	2
9	C	2004	3


Thanks so much for you help!

-----Original Message-----
From: William Dunlap [mailto:wdunlap at tibco.com] 
Sent: Tuesday, October 30, 2012 1:07 PM
To: Meredith, Christy S -FS; r-help at R-project.org
Subject: RE: [R] help with for loop: new column giving count of observation for each SITEID

Is this what you want?
  > withinGroupIndex <- function(group, ...) ave(integer(length(group)), group, ..., FUN=seq_along)
  > site <- c("A","A","C","D","C","A","B")
  > data.frame(site, index=withinGroupIndex(site))
    site index
  1    A     1
  2    A     2
  3    C     1
  4    D     1
  5    C     2
  6    A     3
  7    B     1

You can add more arguments if the groups depend on more than one value:
  > year <- rep(c(1985, 2012), c(4,3))
  > data.frame(site, year, index=withinGroupIndex(site, year))
    site year index
  1    A 1985     1
  2    A 1985     2
  3    C 1985     1
  4    D 1985     1
  5    C 2012     1
  6    A 2012     1
  7    B 2012     1

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com