[R] Average regions of non-zeros

Linlin Yan yanlinlin82 at gmail.com
Mon Mar 8 15:22:20 CET 2010


Nice shot of cumsum(). Just improve it a little:

> x <- c(0,0,1,2,3,0,0,4,5,6)
> x.groups <- split(x, (x != 0) * cumsum(x == 0))[-1]
> x.groups
$`2`
[1] 1 2 3

$`4`
[1] 4 5 6

> lapply(x.groups, mean)
$`2`
[1] 2

$`4`
[1] 5

On Mon, Mar 8, 2010 at 11:02 AM, jim holtman <jholtman at gmail.com> wrote:
> 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 Microsoft’s 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]]
>
>
> ______________________________________________
> 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
> and provide commented, minimal, self-contained, reproducible code.
>
>



More information about the R-help mailing list