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)
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
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:
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,
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
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))
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
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 =