[R] subtotal, submean, aggregate

2006-02-26 Thread Patrick Giraudoux
Dear All, I would like to make partial sums (or means or any other function) of the values in intervals along a sequence (spatial transect) where groups are defined. For instance: habitats-rep(c(meadow,forest,meadow,pasture),c(10,5,12,6)) observations-rpois(length(habitats),2)

Re: [R] subtotal, submean, aggregate

2006-02-26 Thread Gabor Grothendieck
Create another variable that gives the run number and aggregate on both the habitat and run number removing the run number after aggregating: runno - cumsum(c(TRUE, diff(as.numeric(transect[,2])) !=0)) aggregate(transect[,1], list(obs = transect[,2], runno = runno), sum)[,-2] This does not give

Re: [R] subtotal, submean, aggregate

2006-02-26 Thread Roger Bivand
On Sun, 26 Feb 2006, Patrick Giraudoux wrote: Dear All, I would like to make partial sums (or means or any other function) of the values in intervals along a sequence (spatial transect) where groups are defined. For instance:

Re: [R] subtotal, submean, aggregate

2006-02-26 Thread Patrick Giraudoux
Excellent! I was messing with this problem since the early afternoon. Actually the discrepancy you noticed remaining comes from negative difference in diff(as.numeric(transect[,2])) One can work it around using abs(diff(as.numeric(transect[,2]))). This makes: runno - cumsum(c(TRUE,

Re: [R] subtotal, submean, aggregate

2006-02-26 Thread Patrick Giraudoux
Thanks Roger. Again I learn about a new one: rle(). Though working, get to be a nice Sunday... Cheers, Patrick Roger Bivand a écrit : On Sun, 26 Feb 2006, Patrick Giraudoux wrote: Dear All, I would like to make partial sums (or means or any other function) of the values in intervals

Re: [R] subtotal, submean, aggregate

2006-02-26 Thread Gabor Grothendieck
We are just comparing the difference to 0 so it does not matter if its positive or negative. All that matters is whether its 0 or not. In fact, the runno you calculate with the abs is identical to the one I posted without the abs: runno - cumsum(c(TRUE, abs(diff(as.numeric(transect[,2])))!=0))

Re: [R] subtotal, submean, aggregate

2006-02-26 Thread Patrick Giraudoux
Yes right. Checking some examples, all come out OK. same as your example but I think there are some errors in your example output. Simply the 'errors' observed come simply from the seed in rpois(length(habitats),2) It is unlikely it is the same on your and my computer... Cheers, Patrick

Re: [R] subtotal, submean, aggregate

2006-02-26 Thread Gabor Grothendieck
Yes, that must be it. Probably best to issue a: set.seed(1) as part of the code when posting examples with random numbers. Also here is a variation that uses rle that Roger used together with some elements of the solution I posted: runno - with(rle(as.numeric(transect[,2])), rep(seq(along =