Skip to content
Prev 309407 / 398506 Next

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