# Re: [R] replacing segments of vector by their averages

From: jim holtman <jholtman_at_gmail.com>
Date: Fri, 20 Jun 2008 08:36:34 -0400

Does this give you the results you are expecting:

> m <- c(0.3,0.3,0.3,0.1,0.1,0.5,0.5,0.5,0.5,0.15,0.15,0.3,0.5,0.8)
> m > 0.2

[1] TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE FALSE FALSE  TRUE TRUE TRUE
> m.rle <- rle(m > 0.2)
> offsets <- 1 + c(0, head(cumsum(m.rle\$lengths), -1))
> # initialize the output results
> results <- numeric(length(m.rle\$values))
> results[] <- NA
>
> for (i in seq_along(m.rle\$values)){

```+     if (m.rle\$values[i]){  #numbers > 0.2
+         results[i] <- mean(m[seq(offsets[i], length=m.rle\$lengths[i])])
+     }
+ }

> results
[1] 0.3000000        NA 0.5000000        NA 0.5333333
```

>

On Thu, Jun 19, 2008 at 4:55 AM, Daren Tan <daren76_at_hotmail.com> wrote:
>
> Given a vector of numeric of length n, I need to find segments that are >= 0.2, compute the average of individual segments, and replace the original values in each segment by their corresponding averages.
>
> For example, there are three segments that are >= 0.2, the average of 1st segment is 0.3, 2nd is 0.5, and the 3rd is 0.5333333
>
>> c(0.3,0.3,0.3,0.1,0.1,0.5,0.5,0.5,0.5,0.15,0.15,0.3,0.5,0.8) [1] 0.30 0.30 0.30 0.10 0.10 0.50 0.50 0.50 0.50 0.15 0.15 0.30 0.50 0.80> m >= 0.2 [1] TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE FALSE FALSE TRUE[13] TRUE TRUE
>
> _________________________________________________________________
>
>
> [[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.
>

```--
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?

______________________________________________
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.
```
Received on Fri 20 Jun 2008 - 13:13:38 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Fri 20 Jun 2008 - 14:30:58 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.