[R] Average regions of non-zeros
bogaso.christofer
bogaso.christofer at gmail.com
Mon Mar 8 09:26:09 CET 2010
Hi Jim I was following this thread and found that your answer is perfect
there. However I could not comprehend the meaning of the expression "
cumsum(x == 0)". If I paste it in R window, I get following :
> cumsum(x == 0)
[1] 1 2 2 2 2 3 4 4 4 4
I gone through the help page of cumsum() function I correctly understand
that this function calculates the cumulative sum. But could not understand
really the meaning of cumsum(x == 0)
Would you please explain that?
Thanks,
-----Original Message-----
From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-project.org] On
Behalf Of jim holtman
Sent: 08 March 2010 08:32
To: Daren Tan
Cc: r-help at stat.math.ethz.ch
Subject: Re: [R] Average regions of non-zeros
Try this:
> x <- c(0,0,1,2,3,0,0,4,5,6)
> # partition the data
> x.p <- split(x, cumsum(x == 0))
> # now only process groups > 1
> x.mean <- lapply(x.p, function(a){
+ if (length(a) == 1) return(NULL)
+ return(list(grp=tail(a, -1), mean=mean(tail(a, -1))))
+ })
> # now only return the real values
> x.mean[unlist(lapply(x.mean, length) != 0)]
$`2`
$`2`$grp
[1] 1 2 3
$`2`$mean
[1] 2
$`4`
$`4`$grp
[1] 4 5 6
$`4`$mean
[1] 5
On Sun, Mar 7, 2010 at 9:48 PM, Daren Tan <daren76 at hotmail.com> wrote:
>
> x <- c(0,0,1,2,3,0,0,4,5,6)
>
>
>
> How to identify the regions of non-zeros and average c(1,2,3) and c(4,5,6)
> to get 2 and 5.
>
>
>
> Thanks
>
>
>
> _________________________________________________________________
> Hotmail: Trusted email with Microsofts powerful SPAM protection.
>
> [[alternative HTML version deleted]]
>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
>
http://www.R-project.org/posting-guide.html<http://www.r-project.org/posting
-guide.html>
> and provide commented, minimal, self-contained, reproducible code.
>
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
[[alternative HTML version deleted]]
More information about the R-help
mailing list