Renumbering observations with lapply

6 views
Skip to first unread message

pgo...@fs.fed.us

unread,
Oct 8, 2008, 10:27:09 AM10/8/08
to Forest-R
Hello all. I'm an avid R user and I plan to post more to this group
when I get a chance. I've found that I often need to renumber
observation by plot, etc. One example is in creating treelists that
will be run through the US Forest Services' FVS growth model. There is
a nifty shortcut for doing this that is shown in the example below. I
hope that others find it useful.

##create synthetic dataset
tree1 = data.frame(PLOT = rep(seq(1,10),times=round(runif(10)*20+1)))
tree1$DBH = round(runif(length(tree1[,1]))*24,1)
##sort by plot and ascending DBH
ord = order(tree1$PLOT,tree1$DBH)
tree1 = tree1[ord,]

##number observations by plot THIS IS THE INTERESTING PART!!!!
tree1$TreeNo = unsplit(lapply(split(rep(1,length(tree1[,
1])),tree1$PLOT),cumsum),tree1$PLOT)
##rearrange columns
tree1 = subset(tree1,select=c(PLOT,TreeNo,DBH))

Andrew Robinson

unread,
Oct 8, 2008, 4:59:18 PM10/8/08
to for...@googlegroups.com
Nice work!

Here's another version:

tree1$TreeNo <-
unlist(tapply(tree1$PLOT, tree1$PLOT, function(x) seq(length(x))))

Cheers

Andrew

--
Andrew Robinson
Department of Mathematics and Statistics Tel: +61-3-8344-6410
University of Melbourne, VIC 3010 Australia Fax: +61-3-8344-4599
http://www.ms.unimelb.edu.au/~andrewpr
http://blogs.mbs.edu/fishing-in-the-bay/

Reply all
Reply to author
Forward
0 new messages